受到我自己的回答的启发,我什至自己都不明白它是如何工作的,请考虑以下几点:
def has22(nums):
it = iter(nums)
return any(x == 2 == next(it) for x in it)
>>> has22([2, 1, 2])
False
我预计 aStopIteration
会被提出,因为在达到 时2
,next(it)
将推进一个消耗的迭代器。但是,这种行为似乎已被完全禁用,仅适用于生成器表达式!一旦发生这种情况,生成器表达式似乎立即出现break
。
>>> it = iter([2, 1, 2]); any(x == 2 == next(it) for x in it)
False
>>> it = iter([2, 1, 2]); any([x == 2 == next(it) for x in it])
Traceback (most recent call last):
File "<pyshell#114>", line 1, in <module>
it = iter([2, 1, 2]); any([x == 2 == next(it) for x in it])
StopIteration
>>> def F(nums):
it = iter(nums)
for x in it:
if x == 2 == next(it): return True
>>> F([2, 1, 2])
Traceback (most recent call last):
File "<pyshell#117>", line 1, in <module>
F([2, 1, 2])
File "<pyshell#116>", line 4, in F
if x == 2 == next(it): return True
StopIteration
即使这样也有效!
>>> it=iter([2, 1, 2]); list((next(it), next(it), next(it), next(it))for x in it)
[]
所以我想我的问题是,为什么要为生成器表达式启用这种行为?
注意:相同的行为3.x