繁体   English   中英

如何挑选清单的特定部分?

[英]How to pick out specific parts of a list?

所以我有这个清单:

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中只有第一个列表(即[1000, 500, 200, 100, 700, 350, 120, 900, 800] 1000、500、200、100、700、350、120、900、800 [1000, 500, 200, 100, 700, 350, 120, 900, 800] ),那么如何获得答案[500, 350, 120] 500、350、120]。 但是,我不确定如何使用包含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

出现IndexError: list index out of rangeComp是只有2个元素的列表。 索引1处的元素是第二个列表( [1001, 501, 201, 101, 701, 351, 121, 901, 801] ),但是Comps中索引5处没有元素。

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

>>> 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])

您快到了,只需要嵌套一层即可:

[[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)]

由于有一个类似的清单:

1) math=[one, list]您始终使用mathList = math[theIndexOfItemInList]

但由于存在两个或多个,因此您需要更改对列表的计数方式,例如是否有列表:

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

当您调用此列表时:

3) mathList = math[whichListYouNeed][theIndexOfItemInList]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM