問題描述
import itertools
ws=[]
subs=[]
set_subs=[]
for i in xrange(int(raw_input())):
S=raw_input()
l=len(S)
subs.append(S[i:j+1] for i in xrange(l) for j in xrange(i,l))
輸入:
2
aab
aac
現在 subs[0]
和 subs[1]
都給了我相同的結果.
now both subs[0]
and subs[1]
give me same result.
print list(subs[0])
>>>['a','aa','aac','a','ac','c']
print list(subs[1])
>>>['a','aa','aac','a','ac','c']
而 list(subs[0])
應該是 ['a','aa','aab','a','ab','b']代碼>
我隱約明白為什么會這樣.我該怎么做才能使 subs[0]
和 subs[1]
真正不同.
I vaguely understand why this is happening. What do I do to make subs[0]
and subs[1]
actually different.
注意:換行
subs.append(S[i:j+1] for i in xrange(l) for j in xrange(i,l))
與
subs.append([S[i:j+1] for i in xrange(l) for j in xrange(i,l)])
不是一種選擇
推薦答案
http://docs.python.org/reference/expressions.html#generator-expressions
生成器表達式中使用的變量在以下情況下被延遲計算為生成器對象調用 __next__()
方法(在同一像普通發電機一樣時尚).但是,最左邊的 for 子句是立即評估,以便可以看到它產生的錯誤在處理生成器的代碼中出現任何其他可能的錯誤之前表達.無法立即評估后續 for 子句因為它們可能依賴于前面的 for 循環.
Variables used in the generator expression are evaluated lazily when the
__next__()
method is called for generator object (in the same fashion as normal generators). However, the leftmost for clause is immediately evaluated, so that an error produced by it can be seen before any other possible error in the code that handles the generator expression. Subsequent for clauses cannot be evaluated immediately since they may depend on the previous for loop.
S[i:j+1]
在您執行生成器時進行評估,此時 S
具有最新值.
S[i:j+1]
is evaluated when you execute the generator, and at that point S
has the latest value.
您可以改用普通的生成器.現在 ss
對 subgen
來說是本地的:
You can use a normal generator instead. Now ss
is local to subgen
:
import itertools
def subgen(ss):
l=len(ss)
for i in xrange(l):
for j in xrange(i,l):
yield ss[i:j+1]
subs=[]
for i in xrange(int(raw_input())):
S=raw_input()
subs.append(subgen(S))
這篇關于Python 生成器行為的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!