understanding zip function(了解 zip 功能)
问题描述
所有讨论都是关于 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))
(如果迭代).tuple
调用将其转换为 (next(iter(c1)), next(iter(c2)), next(iter(c3))
,用尽其参数 (iterables
) 在第一次调用时,据我所知.我不明白 while
循环如何设法继续,因为它检查 iterables
; 如果它确实继续为什么 tuple
调用不返回空元组(迭代器被耗尽).
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 功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:了解 zip 功能


基础教程推荐
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01