我能';在Python的itertools中找不到imap()

我能';在Python的itertools中找不到imap(),python,iterator,Python,Iterator,我有一个问题要用itertools.imap()解决。但是,在我将itertools导入空闲shell并调用itertools.imap()之后,空闲shell告诉我itertools没有属性imap。怎么了 >>> import itertools >>> dir(itertools) ['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper', '_tee'

我有一个问题要用itertools.imap()解决。但是,在我将itertools导入空闲shell并调用itertools.imap()之后,空闲shell告诉我itertools没有属性imap。怎么了

>>> import itertools
>>> dir(itertools)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper',     '_tee', '_tee_dataobject', 'accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest']
>>> itertools.imap()
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
itertools.imap()
AttributeError: 'module' object has no attribute 'imap'
导入itertools >>>主任(资讯科技工具) [''文档''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' >>>itertools.imap() 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 itertools.imap() AttributeError:“模块”对象没有属性“imap”
您使用的是Python 3,因此在
itertools
模块中没有
imap
函数。它已被删除,因为全局函数现在返回迭代器。

itertools.imap()
在Python2中,但在Python3中不存在

python <path_to_python_installation>\Tools\scripts\2to3.py -w <your_file>.py

实际上,该函数被移动到Python 3中的
map
函数中,如果您想使用旧的Python 2映射,必须使用
list(map())

如果您想要同时在Python 3和Python 2中工作的东西,可以执行以下操作:

try:
    from itertools import imap
except ImportError:
    # Python 3...
    imap=map
这个怎么样

imap = lambda *args, **kwargs: list(map(*args, **kwargs))
事实上!!:)

我喜欢通用Python 2/3代码,如下所示:

# Works in both Python 2 and 3:
from builtins import map
然后,您必须重构代码,以便在使用
imap
之前的任何地方使用
map

myiter = map(func, myoldlist)

# `myiter` now has the correct type and is interchangeable with `imap`
assert isinstance(myiter, iter)
您确实需要安装future才能在2和3上使用:

pip install future

可以使用2to3脚本()将程序或整个项目从Python2转换为Python3,2to3脚本()是每个Python安装的一部分

python <path_to_python_installation>\Tools\scripts\2to3.py -w <your_file>.py
python\Tools\scripts\2to3.py-w.py

(-w选项将修改写入文件,将存储备份)

谢谢,伙计,我也尝试导入accumulate,但无法工作。问题是python2.x,现在切换到python3.x,它开始工作了。在python3中看一看也很有趣。