私自身の答えに触発されて、私はそれがどのように機能するかさえ理解していませんでした。次のことを考慮してください。
def has22(nums):
it = iter(nums)
return any(x == 2 == next(it) for x in it)
>>> has22([2, 1, 2])
False
StopIteration
に到達すると、消費されたイテレータが進むため、 a が発生すること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