下在Python 3.6从不打印任何东西itertools.product懒惰地评估它的参数吗?
from itertools import product, count
for f in product(count(), [1,2]):
print(f)
相反,它只是坐在那里和烧伤CPU。这个问题似乎是,product
永远不会返回迭代器,因为它首先评估整个product
。这是令人惊讶的,因为product
应该是一个发电机。
我本来期望这开始计数(到无穷大),这样的事情发生(采取directly from the docs)的行为:
for tup in ((x,y) for x in count() for y in [1,2]):
print(tup)
但是,尽管我的发电机立即启动算起,一个使用product
从未根本算不算什么。
itertools
的其他工具做我期望的。例如,以下内容:
for f in takewhile(lambda x: True, count()):
print(f)
将打印一串数字,因为takewhile
是懒惰的。
DeepSpace的答案是误导性的:据我所知,产品不是懒惰,因为它需要(我假设)无限的时间来返回,而文档中的等价示例却如我所料。 – Shep