【问题标题】:why return empty list when calling list on zip twice [duplicate]为什么在两次调用zip上的列表时返回空列表[重复]
【发布时间】:2021-05-22 22:31:16
【问题描述】:

如下python代码所示,为什么调用第二个list(ll)时会打印空列表?

l1 = [1,2,3]
l2 = [4,5,6]
ll = zip(l1,l2,l1,l2)
ll
<zip at 0x23d50b10f40>
list(ll)
[(1, 4, 1, 4), (2, 5, 2, 5), (3, 6, 3, 6)]
ll
<zip at 0x23d50b10f40>
list(ll)
[]

【问题讨论】:

    标签: python list


    【解决方案1】:

    因为zip 是一个迭代器对象。当您第一次调用 list(ll) 时,zip 对象中的值会被消耗。这就是为什么当您再次拨打list 时,没有其他内容可显示。

    zip 是一个函数,当应用于可迭代对象时,它会返回一个迭代器。意思是,除非它被迭代,否则它不会计算任何值。

    例如:

    >>> z = zip([1, 2, 3], [3, 4, 5])
    >>> z
    <zip at 0x1e46824bec0>
    
    >>> next(z)    # One value is computed, thus consumed, now if you call list:
    (1, 3)
    
    >>> list(z)    # There were only two left, and now even those two are consumed
    [(2, 4), (3, 5)]
    
    >>> list(z)    # Returns empty list because there is nothing to consume
    []
    

    【讨论】:

      猜你喜欢
      • 2020-09-27
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 2015-01-27
      • 1970-01-01
      • 1970-01-01
      • 2016-07-03
      相关资源
      最近更新 更多