强制转换为列表的副作用?

时间:2018-12-23 17:31:02

标签: python list casting side-effects

我有一个(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

1 个答案:

答案 0 :(得分: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)
[]