leisurelicht/wtfpython-cn

About Evaluation time discrepancy/执行时机差异

Closed this issue · 3 comments

>>> array=[1,8,15]
>>> g=(x for x in array if array.count(x)>0)
>>> array=[2,8,22]
>>> list(g)
[8]
>>> array=[1,8,15]
>>> g=(x for x in array if array.count(x)>0)
>>> list(g)
[1, 8, 15]
>>> array=[2,8,22]
>>> list(g)
[]

Why?

ch-yx commented
>>> a=[1,2]
>>> g=(i for i in a)
>>> list(g)
[1, 2]
>>> list(g)
[]
>>> 

因为你在list(g)的时候把g消耗了

ch-yx commented

和执行时机差异没关系。
这个g就是只能用一次。
即使是(i for i in a)这样什么运算也没有也是如此

python中这种小括号括起来的情况叫生成器表达式,返回的是一个生成器。而python中的生成器只能迭代一次。list操作会进行一次迭代导致生成器被使用。