izip不工作在Python 3.x [英] izip not working in Python 3.x
问题描述
我要导入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.
推荐答案
在oython3中,内置的 zip
与2.X中的 izip
相同的工作(返回一个生成器而不是列表),但是稍快一些,因为它是一个内置函数。
In oython3 the built in zip
does the same job as izip
in 2.X (returns a generator instead of a list) but slightly faster as it's a built-in function.
这里是python 2和3中的 zip
之间的一个长凳;在python 2中的 izip
Here is a benchmarck between zip
in python 2 and 3 and izip
in python 2:
Pyhon 2.7:
Pyhon 2.7:
In [5]: %timeit list(izip(range(100), range(100)))
100000 loops, best of 3: 5.16 µs per loop
In [6]: %timeit zip(range(100), range(100))
100000 loops, best of 3: 3.87 µs per loop
python 3:
In [2]: %timeit list(zip(range(100), range(100)))
100000 loops, best of 3: 3.84 µs per loop
在这种情况下,因为 zip
的参数必须支持迭代,你不能使用2作为其参数。所以如果你想写一个csv行2变量,你可以把它们放在一个元组或列表:
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.
这篇关于izip不工作在Python 3.x的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!