【发布时间】:2017-01-05 23:58:29
【问题描述】:
为什么list(next(iter(())) for _ in range(1)) 返回一个空列表而不是提升StopIteration?
>>> 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)) # ?!
[]
【问题讨论】:
-
哇,我真的很喜欢原来“重复”问题中的答案!
-
这是一个错误,正在使用PEP 479 解决,其中
StopIteration将转换为RuntimeError,这样列表就不会像您期望的那样错误地停止迭代. -
@TadhgMcDonald-Jensen 请给出答案,以便我投票。
-
为了后代,这里是提到的"duplicate" questionwheaties。