Skip to main content
 首页 » 编程设计

python之如何挑选列表的特定部分

2025年05月04日23lautakyan007

所以我有这个列表:

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

如果只有第一个列表(即 [1000, 500, 200, 100, 700, 350),我知道如何得到答案 [500, 350, 120] , 120, 900, 800]) 在变量 Comps 中。但是,我不确定如何使用包含 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 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])