这两个代码片段仅在构造列表的方式上有所不同。一个使用[]
,另一个使用list()
。你知道吗
这个函数消耗iterable,然后引发StopIteration
:
>>> try:
... iterable = iter(range(4))
... while True:
... print([next(iterable) for _ in range(2)])
... except StopIteration:
... pass
...
[0, 1]
[2, 3]
这个函数消耗iterable并循环打印空列表。你知道吗
>>> try:
... iterable = iter(range(4))
... while True:
... print(list(next(iterable) for _ in range(2)))
... except StopIteration:
... pass
...
[0, 1]
[2, 3]
[]
[]
[]
etc.
这种行为的规则是什么?你知道吗
参考PEP479,它说
(我的重点)
因此
list
的构造函数对传递的生成器表达式进行迭代,直到引发StopIteration
错误(通过调用next(iterable)
而不使用第二个参数)。另一个例子:另一方面,*理解的工作方式不同,因为它们将
StopIteration
传播给调用者。你知道吗相关政治公众人物提议的行为如下
python3.5添加了^{} feature ,可以使用
这种行为在python3.7中是默认的。你知道吗
相关问题 更多 >
编程相关推荐