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

29 python iterator

我有一个问题,我想用itertools.imap()来解决.但是,在我在IDLE shell中导入itertools并调用itertools.imap()后,IDLE 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'
Run Code Online (Sandbox Code Playgroud)

mar*_*kzz 32

itertools.imap() 是在Python 2中,但在Python 3中没有.

实际上,该功能只是移动到mapPython 3中的功能,如果你想使用旧的Python 2地图,你必须使用list(map()).

  • 谢谢朋友,我也尝试导入累积,但没有成功。问题是 python2.x ,现在切换到 python3.X 它开始工作 (2认同)

daw*_*awg 15

如果你想要一些适用于Python 3和Python 2的东西,你可以这样做:

try:
    from itertools import imap
except ImportError:
    # Python 3...
    imap=map
Run Code Online (Sandbox Code Playgroud)


Ali*_*lik 6

您正在使用Python 3,因此模块中没有imap功能itertools.它被删除了,因为全局函数map现在返回迭代器.