【问题标题】:Failing to import itertools in Python 3.5.2无法在 Python 3.5.2 中导入 itertools
【发布时间】:2016-12-02 18:05:39
【问题描述】:

我是 Python 新手。我正在尝试从 itertools 导入 izip_longest。但我无法在 Python 解释器的首选项中找到导入“itertools”。我正在使用 Python 3.5.2。它给了我以下错误-

from itertools import izip_longest
ImportError: cannot import name 'izip_longest'

请告诉我正确的做法是什么。我也尝试过 Python 2.7 并遇到了同样的问题。是否需要使用低版本的 Python。

【问题讨论】:

    标签: python python-2.7 pycharm python-3.5 itertools


    【解决方案1】:

    导入任何功能的一种简单方法是通过对象导入(例如:import itertools as it),除非您想隐藏其他功能。由于模块中的功能确实会根据 python 版本而变化,因此检查模块中是否存在该功能的简单方法是通过 dir() 函数。 导入 itertools 目录(它) 它将列出其中的所有功能

    【讨论】:

      【解决方案2】:

      izip_longest 在 Python 3 中重命名zip_longest(注意,开头没有 i),改为导入:

      from itertools import zip_longest
      

      并在您的代码中使用该名称。

      如果您需要编写同时适用于 Python 2 和 3 的代码,请捕获 ImportError 以尝试其他名称,然后重命名:

      try:
          # Python 3
          from itertools import zip_longest
      except ImportError:
          # Python 2
          from itertools import izip_longest as zip_longest
      
      # use the name zip_longest
      

      【讨论】:

      • 谢谢@Martijn。将其更改为 zip_longest 解决了我的问题。
      猜你喜欢
      • 2017-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 2017-08-20
      • 2017-05-04
      • 2017-10-01
      相关资源
      最近更新 更多