且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从 itertools 模块导入 izip 在 Python 3.x 中给出 NameError

更新时间:2023-11-18 18:23:28

在 Python 3 中,内置的 zip 与 2 中的 itertools.izip 完成相同的工作.X(返回一个迭代器而不是一个列表).zip 实现 几乎完全从 复制粘贴izip,只是更改了一些名称并添加了pickle 支持.

In Python 3 the built-in zip does the same job as itertools.izip in 2.X(returns an iterator instead of a list). The zip implementation is almost completely copy-pasted from the old izip, just with a few names changed and pickle support added.

这是 Python 2 和 3 中的 zip 与 Python 2 中的 izip 之间的基准:

Here is a benchmark between zip in Python 2 and 3 and izip in Python 2:

Python 2.7:

from timeit import timeit

print(timeit('list(izip(xrange(100), xrange(100)))',
             'from itertools import izip',
             number=500000))

print(timeit('zip(xrange(100), xrange(100))', number=500000))

输出:

1.9288790226
1.2828938961

Python 3:

from timeit import timeit

print(timeit('list(zip(range(100), range(100)))', number=500000))

输出:

1.7653984297066927

在这种情况下,由于 zip 的参数必须支持迭代,因此您不能使用 2 作为其参数.因此,如果您想将 2 个变量写为 CSV 行,您可以将它们放在一个元组或列表中:

In this case since zip's arguments must support iteration you can not use 2 as its argument. So if you want to write 2 variable as a CSV row you can put them in a tuple or list:

writer.writerows((variable1,2))

也可以从 itertools 导入 zip_longest 作为一个更灵活的函数,你可以在不同大小的迭代器上使用它.

Also from itertools you can import zip_longest as a more flexible function which you can use it on iterators with different size.