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 功能
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
