なぜlist(next(iter(())) for _ in range(1))
は、StopIteration
を呼び出すのではなく、空のリストを返しますか?なぜrange(1)の_のnext(iter(()))== []ですか?
>>> next(iter(()))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> [next(iter(())) for _ in range(1)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> list(next(iter(())) for _ in range(1)) # ?!
[]
同じことが明示的にStopIteration
を上げるカスタム関数で発生します:
>>> def x():
... raise StopIteration
...
>>> x()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in x
StopIteration
>>> [x() for _ in range(1)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in x
StopIteration
>>> list(x() for _ in range(1)) # ?!
[]
私は本当に元の「重複した」質問の答えが好きです! – wheaties
これはバグです。[PEP 479](http://legacy.python.org/dev/peps/pep-0479/)で対処されています。ここで 'StopIteration'は' RuntimeError'に変換されます。あなたが期待しているとおり、リストは反復を間違って停止しません。 –
@ TadhgMcDonald-Jensen私はそれを投票することができるように答えてください。 – wheaties