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

查看:35
本文介绍了从 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 中的 itertools.izip 完成相同的工作.X(返回一个迭代器而不是一个列表).zip 实现 几乎完全从 复制粘贴izip,只是更改了一些名称并添加了pickle 支持.

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天全站免登陆