简体   繁体   English

从python中的列表列表中选择一个子列表

[英]select a sublist from a list of lists in python

I've got a list of lists A : 我有一个列表A的列表:

A = [ [0, 42, 2.6],
      [1, 20, 5.6],
      [2, 67, 3.5],
      [3, 12, 3.2],
      [4, 34, 1.1],
      [5, 74, 4.7],
      [6, 29, 2.9] ]

from which I'd like to extract a sub-list B containing only those lists whose second columns are lower than 30 (ie, B = [[1, 20, 5.6],[3, 12, 3.2],[6, 29, 2.9]] ) 我想从中提取一个子列表B ,该子列表B仅包含第二列小于30的那些列表(即B = [[1, 20, 5.6],[3, 12, 3.2],[6, 29, 2.9]]

Of course I may convert it to a numpy and use a np.where . 当然,我可以将其转换为numpy并使用np.where However I was wondering whether there is a way of doing that just by using lists. 但是我想知道是否只有通过使用列表才能做到这一点。 I tried with a list comprehension, but I'm not very expert on that: 我尝试了列表理解,但是在这方面我不是很熟练:

B = [x for x in len(A) if x[1] <= 30]

but it doesn't work, indeed. 但这确实不起作用。 Any suggestion? 有什么建议吗? Thanks in advance. 提前致谢。

尝试这个:

B = [x for x in A if x[1] <= 30]

Your current code is attempting to generate an value to be used as an index at each iteration. 您当前的代码正在尝试生成一个值,该值将在每次迭代时用作索引。 To implement that approach, access each row of A with x : 要实现该方法,请使用x访问A每一行:

B = [A[x] for x in range(len(A)) if A[x][1] <= 30]

Note, however, that is much simpler to use a list comprehension or the more functional filter : 但是请注意,使用列表推导或更实用的filter要简单得多:

List comprehension: 清单理解:

B = [i for i in A if i[1] <= 30]

filter : filter

B = list(filter(lambda x:x[1] <= 30, A))

Here is a vectorised approach: 这是一种向量化方法:

import numpy as np

A = np.array([[0, 42, 2.6],
             [1, 20, 5.6],
             [2, 67, 3.5],
             [3, 12, 3.2],
             [4, 34, 1.1],
             [5, 74, 4.7],
             [6, 29, 2.9]])

A[A[:, 1] <= 30]

# array([[  1. ,  20. ,   5.6],
#        [  3. ,  12. ,   3.2],
#        [  6. ,  29. ,   2.9]])

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

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