【问题标题】:How to make zip_longest available in itertools using Python 2.7如何使用 Python 2.7 使 zip_longest 在 itertools 中可用
【发布时间】:2017-06-10 21:11:10
【问题描述】:

尝试在 Windows 10 上运行的 Python Jupyter 2.7 nb 上导入此函数时,我收到此错误:

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

【问题讨论】:

    标签: python python-2.7 itertools


    【解决方案1】:

    对于 Python 3,方法是 zip_longest:

    from itertools import zip_longest
    

    对于 Python 2,方法是 izip_longest:

    from itertools import izip_longest
    

    【讨论】:

    • 目前的积分 - 将在允许时接受(6 分钟)。泰
    • 很高兴能帮上忙!
    • 不要忘记,在 Python 3 中,map 和 zip 函数返回迭代器而不是列表,因此如果您需要一个列表,则需要 list() 它们。我经常被这个烧伤。我恨它。但是懒惰的评价才是王道。
    【解决方案2】:

    如果你不知道哪个版本的 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])))
    

    【讨论】:

      猜你喜欢
      • 2020-04-07
      • 2018-11-06
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 2020-02-03
      • 2018-06-08
      • 1970-01-01
      • 2017-11-04
      相关资源
      最近更新 更多