从 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 zipdoes the same job as itertools.izipin 2.X(returns an iterator instead of a list). The zipimplementationis almost completely copy-pasted from the old izip, just with a few names changed and pickle support added.
在 Python 3 中,内置zip函数与itertools.izip2.X中的工作相同(返回迭代器而不是列表)。该zip实现几乎完全从旧的izip复制粘贴,只是更改了一些名称并添加了泡菜支持。
Here is a benchmark between zipin Python 2 and 3 and izipin Python 2:
这是zipPython 2 和 3 以及izipPython 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 itertoolsyou can import zip_longestas 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

