我无法在Python的itertools中找到imap()。

2024-04-24 07:15:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题要用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'

Tags: nameimportpackagedoc属性dirloadershell
3条回答

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

try:
    from itertools import imap
except ImportError:
    # Python 3...
    imap=map

您正在使用Python 3,因此在itertools模块中没有imap函数。它已被删除,因为全局函数^{}现在返回迭代器。

itertools.imap()在Python 2中,而不是在Python 3中。

实际上,在Python 3中,该函数只被移到了map函数,如果要使用旧的Python 2映射,则必须使用list(map())

相关问题 更多 >