了解 zip 功能

时间:2023-01-25
本文介绍了了解 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 功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:使用迭代器的最快(最 Pythonic)方式 下一篇:csv.DictReader 中的行数

相关文章

最新文章