【问题标题】:Side effect of casting to a list? [duplicate]投射到列表的副作用? [复制]
【发布时间】:2019-05-23 03:51:33
【问题描述】:

我有一个 (x,y) 元组列表(在下面的示例中为“lt”)。我想提取 x 和 y,以便执行 Pearson 相关计算。如果我执行这段代码:

lt = [(1,2), (3,4), (5,6)]
print(lt)
unzip_list = zip(*lt)
xs = list(unzip_list)[0]
print(xs)

不出所料,我得到了这个结果:

[(1, 2), (3, 4), (5, 6)]
(1, 3, 5)

如果我执行这段代码:

lt = [(1,2), (3,4), (5,6)]
print(lt)
unzip_list = zip(*lt)
ys = list(unzip_list)[1]
print(ys)

不出所料,我得到了这个结果:

[(1, 2), (3, 4), (5, 6)]
(2, 4, 6)

但是如果我执行这段代码:

lt = [(1,2), (3,4), (5,6)]
print(lt)
unzip_list = zip(*lt)
xs = list(unzip_list)[0]
print(xs)
ys = list(unzip_list)[1]
print(ys)

我在第 6 行收到此错误!

[(1, 2), (3, 4), (5, 6)]
(1, 3, 5)

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-302-81d917cf4b2d> in <module>()
      4 xs = list(unzip_list)[0]
      5 print(xs)
----> 6 ys = list(unzip_list)[1]
      7 print(ys)

IndexError: list index out of range

【问题讨论】:

    标签: python list casting side-effects


    【解决方案1】:

    zip 返回一个迭代器,所以一旦你在它上面调用list,它就会变空

    Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
    [GCC 8.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> zip([1], [1])
    <zip object at 0x7fcd991991c8>
    >>> a = zip([1], [1])
    >>> list(a)
    [(1, 1)]
    >>> list(a)
    []
    

    您可以使用tee 获取多个迭代器:

    >>> from itertools import tee
    >>> a, b = tee(zip([1], [1]), 2)
    >>> list(a)
    [(1, 1)]
    >>> list(b)
    [(1, 1)]
    >>> list(a)
    []
    >>> list(b)
    []
    

    【讨论】:

      猜你喜欢
      • 2018-06-21
      • 1970-01-01
      • 2012-02-13
      • 2017-07-03
      • 1970-01-01
      • 2021-11-18
      • 2019-04-08
      • 2020-06-02
      • 2016-09-17
      相关资源
      最近更新 更多