无法在 Python 3.5.2 中导入 itertools
Failing to import itertools in Python 3.5.2
我是 Python 的新手。我正在尝试从 itertools 导入 izip_longest。但是我无法在 Python 解释器的首选项中找到 import "itertools" 。我正在使用 Python 3.5.2。它给了我以下错误-
from itertools import izip_longest
ImportError: cannot import name 'izip_longest'
请告诉我什么是正确的做法。我也试过 Python 2.7,结果遇到了同样的问题。是否需要使用低版本Python.
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
导入任何功能的一种简单方法是通过对象导入(例如:按原样导入 itertools),除非您想隐藏其他功能。由于模块中的功能确实会根据 python 版本发生变化,因此检查模块中是否存在该功能的简单方法是通过 dir() 函数。
按原样导入 itertools
目录(它)
它将列出其中的所有功能
我是 Python 的新手。我正在尝试从 itertools 导入 izip_longest。但是我无法在 Python 解释器的首选项中找到 import "itertools" 。我正在使用 Python 3.5.2。它给了我以下错误-
from itertools import izip_longest
ImportError: cannot import name 'izip_longest'
请告诉我什么是正确的做法。我也试过 Python 2.7,结果遇到了同样的问题。是否需要使用低版本Python.
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
导入任何功能的一种简单方法是通过对象导入(例如:按原样导入 itertools),除非您想隐藏其他功能。由于模块中的功能确实会根据 python 版本发生变化,因此检查模块中是否存在该功能的简单方法是通过 dir() 函数。 按原样导入 itertools 目录(它) 它将列出其中的所有功能