8
为了更好地理解Python的发电机我试图实现itertools
模块中的设施,并陷入困境与izip
:为什么izip()的这个实现不起作用?
def izip(*iterables):
its = tuple(iter(it) for it in iterables)
while True:
yield tuple(next(it) for it in its) # ERROR
# yield tuple(map(next, its)) # OK
我的代码使用错误行,并参考实现(在手册中给出)使用OK线,不考虑其他微小差异。在这个片段:
for x in izip([1, 2, 3], (4, 5)):
print x
我的代码输出:
(1, 4)
(2, 5)
(3,)
()
()
... # indefinite()
,而预期输出是:
(1, 4)
(2, 5)
有什么错我的代码,好吗?
@wdscxsj:see http://www.velocityreviews.com/forums/t723967-generator-expressions-vs-comprehensions.html – 2012-04-11 15:19:12
@Sven Marnach:谢谢!你的解释很简洁,非常重要。 – wdscxsj 2012-04-11 15:20:37
@Steven Rumbalski:链接页面帮助我更好地理解。谢谢! – wdscxsj 2012-04-11 15:24:07