如何挑选列表的特定部分?

时间:2017-11-06 07:56:32

标签: python

所以我有这个清单:

Comps = [
    [1000, 500, 200, 100, 700, 350, 120, 900, 800],
    [1001, 501, 201, 101, 701, 351, 121, 901, 801]
    ]

如何从此列表中获得结果[500,350,120]和[501,351,121]?

如果变量Comps中只有第一个列表([500, 350, 120]),我知道如何得到答案[1000, 500, 200, 100, 700, 350, 120, 900, 800]。但是,我不知道如何使用包含2个或更多列表的列表(也称为"列表列表")。我一直收到错误:" IndexError:列表索引超出范围"。

我所做的是:

print(list(Comps[i] for i in [1, 5, 6]))

以下是感兴趣的人的完整错误:

    Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    print(list(Comps[i] for i in [1, 5, 6]))
  File "<pyshell#74>", line 1, in <genexpr>
    print(list(Comps[i] for i in [1, 5, 6]))
IndexError: list index out of range

3 个答案:

答案 0 :(得分:3)

获得IndexError: list index out of range的原因是Comp是一个只包含2个元素的列表。索引1处的元素是第二个列表([1001, 501, 201, 101, 701, 351, 121, 901, 801]),但5中的索引Comps没有元素。

您可以使用嵌套列表理解:

>>> Comps = [[1000, 500, 200, 100, 700, 350, 120, 900, 800], [1001, 501, 201, 101, 701, 351, 121, 901, 801]]
>>> [[l[i] for i in [1, 5, 6]] for l in Comps]
[[500, 350, 120], [501, 351, 121]]

如果你想要它们在一个平面列表中:

>>> [l[i] for l in Comps for i in [1, 5, 6]]
[500, 350, 120, 501, 351, 121]

如果你使用矩阵和数组,你可能想看看numpy:

import numpy as np
comps = np.array([[1000, 500, 200, 100, 700, 350, 120, 900, 800], [1001, 501, 201, 101, 701, 351, 121, 901, 801]])
comps[:,[1, 5, 6]]
# array([[500, 350, 120],
#       [501, 351, 121]])

如果您只想要其中一个:

>>> [Comps[0][i] for i in [1, 5, 6]]
[500, 350, 120]
>>> [Comps[1][i] for i in [1, 5, 6]]
[501, 351, 121]

和NumPy一起:

>>> comps[0, [1, 5, 6]]
array([500, 350, 120])
>>> comps[1, [1, 5, 6]]
array([501, 351, 121])

答案 1 :(得分:1)

你几乎就在那里,你只需要更深一层:

[[sub[i] for i in [1, 5, 6]] for sub in Comps]

或者,您可以使用operator.itemgetter

>>> list(map(operator.itemgetter(*[1, 5, 6]), Comps))
[(500, 350, 120), (501, 351, 121)]

或者,更直接地,

>>> list(map(operator.itemgetter(1, 5, 6), Comps))
[(500, 350, 120), (501, 351, 121)]

答案 2 :(得分:1)

因为有一个列表如:

1)math=[one, list]您总是使用mathList = math[theIndexOfItemInList]

但是因为有两个或更多你需要改变你对列表的计算方式,比如有一个列表:

2)math=[[one, list], [second, list], [third, list], [etc, list]]

你打电话给这个名单:

3)mathList = math[whichListYouNeed][theIndexOfItemInList]