从 itertools 模块导入 izip 会在 Python 3.x 中产生 NameError
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32659552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
importing izip from itertools module gives NameError in Python 3.x
提问by iAmNewToPYTHON
I am trying to import the izip module like so:
我正在尝试像这样导入 izip 模块:
from itertools import izip
However after recently changing over from Python 2.7 to 3 - it doesn't seem to work.
然而,在最近从 Python 2.7 转换到 3 之后 - 它似乎不起作用。
I am trying to write to a csv file:
我正在尝试写入 csv 文件:
writer.writerows(izip(variable1,2))
But I have no luck. Still encounter an error.
但我没有运气。还是遇到错误。
回答by Kasramvd
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
implementationis almost completely copy-pasted from the old izip
, just with a few names changed and pickle support added.
在 Python 3 中,内置zip
函数与itertools.izip
2.X中的工作相同(返回迭代器而不是列表)。该zip
实现几乎完全从旧的izip
复制粘贴,只是更改了一些名称并添加了泡菜支持。
Here is a benchmark between zip
in Python 2 and 3 and izip
in Python 2:
这是zip
Python 2 和 3 以及izip
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))
Output:
输出:
1.9288790226
1.2828938961
蟒蛇3:
from timeit import timeit
print(timeit('list(zip(range(100), range(100)))', number=500000))
Output:
输出:
1.7653984297066927
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:
在这种情况下,由于zip
的参数必须支持迭代,因此您不能使用 2 作为其参数。因此,如果您想将 2 个变量写为 CSV 行,您可以将它们放在一个元组或列表中:
writer.writerows((variable1,2))
Also from itertools
you can import zip_longest
as a more flexible function which you can use it on iterators with different size.
此外,itertools
您还可以将其导入zip_longest
为更灵活的函数,您可以在不同大小的迭代器上使用它。
回答by Vasyl Lyashkevych
One of the ways which helped me is:
帮助我的方法之一是:
try:
from itertools import izip as zip
except ImportError: # will be 3.x series
pass