如何在Python 2.7中使用itertools使zip_longest可用

13

当我试图在运行在Windows 10上的Python Jupyter 2.7 nb中导入此函数时,会出现以下错误:

输入图像描述

我认为以前我没有遇到过问题,因为我使用的是Python 3。所以我想知道它是否只是在Python 2中不可用,或者有没有方法可以使其工作。

2个回答

34

对于 Python 3,该方法为 zip_longest

from itertools import zip_longest

对于Python 2, 方法是 izip_longest

from itertools import izip_longest

现在只是暂时的积分 - 我会在允许的时候接受它(6分钟)。谢谢。 - Antoni Parellada
很高兴能够帮助! - Ajax1234
1
不要忘记在Python 3中,map和zip函数返回迭代器而不是列表,因此如果你期望得到一个列表,你需要将它们转换为list()。我经常因此而受挫。我讨厌它。但懒惰求值才是王道。 - RufusVS

9

如果您不知道脚本运行的是哪个python版本,可以使用以下技巧:

try:
    from itertools import zip_longest
except ImportError:
    from itertools import izip_longest as zip_longest

# now this works in both python 2 and 3
print(list(zip_longest([1,2,3],[4,5])))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接