从itertools模块导入izip会在Python 3.x中提供NameError [英] importing izip from itertools module gives NameError in Python 3.x

查看:212
本文介绍了从itertools模块导入izip会在Python 3.x中提供NameError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图像这样导入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:

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.

这篇关于从itertools模块导入izip会在Python 3.x中提供NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆