gpt4 book ai didi

python - 为什么 list(next(iter(())) for _ in range(1)) == []?

转载 作者:IT老高 更新时间:2023-10-28 21:03:28 25 4
gpt4 key购买 nike

为什么 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)) # ?!
[]

最佳答案

假设一切顺利,生成器理解 x() for _ in range(1) 应该在完成对 range(1 的迭代时引发 StopIteration ) 表示没有更多的项目可以打包到列表中。

但是因为 x() 引发 StopIteration 它最终退出早期意味着此行为是 python 中的一个错误,正在通过 PEP 479 解决

在 python 3.6 中或在 python 3.5 中使用 from __future__ import generator_stop 当 StopIteration 传播得更远时,它被转换为 RuntimeError 以便 list 不会将其注册为理解的结束。当这生效时,错误如下所示:

Traceback (most recent call last):
File "/Users/Tadhg/Documents/codes/test.py", line 6, in <genexpr>
stuff = list(x() for _ in range(1))
File "/Users/Tadhg/Documents/codes/test.py", line 4, in x
raise StopIteration
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/Users/Tadhg/Documents/codes/test.py", line 6, in <module>
stuff = list(x() for _ in range(1))
RuntimeError: generator raised StopIteration

关于python - 为什么 list(next(iter(())) for _ in range(1)) == []?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39214961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com