问题描述
我试图像这样导入izip模块:
I am trying to import the izip module like so:
from itertools import izip
但是,在最近从Python 2.7切换到3之后,它似乎不起作用.
However after recently changing over from Python 2.7 to 3 - it doesn't seem to work.
我正在尝试写入一个csv文件:
I am trying to write to a csv file:
writer.writerows(izip(variable1,2))
但是我没有运气.仍然遇到错误.
But I have no luck. Still encounter an error.
推荐答案
在Python 3中,内置的zip
与2.X中的itertools.izip
做相同的工作(返回迭代器而不是列表). zip
实现几乎是完全复制的-从旧izip
粘贴,只是更改了一些名称,并添加了泡菜支持.
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:
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.
这篇关于从itertools模块导入izip会在Python 3.x中提供NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!