了解zip功能 [英] understanding zip function
问题描述
所有讨论都是关于python 3.1.2;请参阅 Python文档了解我的问题来源。
All discussion is about python 3.1.2; see Python docs for the source of my question.
我知道 zip
是做什么的;我只是不明白为什么它可以像这样实现:
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))
假设我打电话给 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)
将它转换为迭代器,如果遍历,它将返回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.
循环内部, map(next,iterables)
是一个迭代器,它将返回 next(iter(c1))
, next(iter(c2))
,然后 next(iter(c3))
如果迭代完毕。 元组
调用将其转换为(next(iter(c1)),next(iter(c2)),next(iter(c3))
,据我所知,在第一次调用时耗尽了它的参数( iterables
)。我不明白 while
循环设法继续,因为它检查 iterables
;如果它确实继续,为什么元组
call不会返回空元组(迭代器已经耗尽)。
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中没有,它进入无限循环。
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.
看起来这个问题在主干文档集上不存在,但你可能应该在 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/.
这篇关于了解zip功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!