問題描述
所有討論都是關(guān)于 python 3.1.2;有關(guān)我的問題的來源,請參閱 Python 文檔.
All discussion is about python 3.1.2; see Python docs for the source of my question.
我知道 zip
是做什么的;我只是不明白為什么可以這樣實現(xiàn):
I know what zip
does; I just don't understand why it can be implemented like this:
def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
iterables = map(iter, iterables)
while iterables:
yield tuple(map(next, iterables))
假設(shè)我調(diào)用 zip(c1, c2, c3)
.如果我理解正確的話,iterables 最初是元組 (c1, c2, c3).
Let's say I call zip(c1, c2, c3)
. If I understand correctly, iterables is initially the tuple (c1, c2, c3).
iterables = map(iter, iterables)
行將其轉(zhuǎn)換為迭代器,如果迭代則返回 iter(c1)、iter(c2)、iter(c3).
The line iterables = map(iter, iterables)
converts it to an iterator that would return iter(c1), iter(c2), iter(c3) if iterated through.
在循環(huán)內(nèi)部,map(next, iterables)
是一個迭代器,它會返回 next(iter(c1))
, next(iter(c2))
和 next(iter(c3))
(如果迭代).tuple
調(diào)用將其轉(zhuǎn)換為 (next(iter(c1)), next(iter(c2)), next(iter(c3))
,用盡其參數(shù) (iterables
) 在第一次調(diào)用時,據(jù)我所知.我不明白 while
循環(huán)如何設(shè)法繼續(xù),因為它檢查 iterables
; 如果它確實繼續(xù)為什么 tuple
調(diào)用不返回空元組(迭代器被耗盡).
Inside the loop, map(next, iterables)
is an iterator that would return next(iter(c1))
, next(iter(c2))
, and next(iter(c3))
if iterated through. The tuple
call converts it to (next(iter(c1)), next(iter(c2)), next(iter(c3))
, exhausting its argument (iterables
) on the very first call as far as I can tell. I don't understand how the while
loop manages to continue given that it checks iterables
; and if it does continue why the tuple
call doesn't return empty tuple (the iterator being exhausted).
我確定我錯過了一些非常簡單的東西..
I'm sure I'm missing something very simple..
推薦答案
看起來這是文檔中的一個錯誤.等效"代碼在 python2 中有效,但在 python3 中無效,進(jìn)入無限循環(huán).
It looks like it's a bug in the documentation. The 'equivalent' code works in python2 but not in python3, where it goes into an infinite loop.
而且最新版本的文檔也有同樣的問題:http://docs.python.org/release/3.1.2/library/functions.html
And the latest version of the documentation has the same problem: http://docs.python.org/release/3.1.2/library/functions.html
看起來更改 61361 是問題,因為它合并了從 python 2.6 更改,但未驗證它們是否適用于 python3.
Looks like change 61361 was the problem, as it merged changes from python 2.6 without verifying that they were correct for python3.
看起來該問題在主干文檔集中不存在,但您可能應(yīng)該在 http://bugs.python.org/.
It looks like the issue doesn't exist on the trunk documentation set, but you probably should report a bug about it at http://bugs.python.org/.
這篇關(guān)于了解 zip 功能的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!