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

新手上路,请多包涵

我有一个问题想用 itertools.imap() 解决。 I imported itertools and called itertools.imap() , but apparently itertools doesn’t have attribute 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'

原文由 user3905370 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 884
2 个回答

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

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

原文由 markzz 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你想要在 Python 3 和 Python 2 中都工作的东西,你可以这样做:

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

原文由 dawg 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏