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