简体   繁体   中英

select a sublist from a list of lists in python

I've got a list of lists 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]] )

Of course I may convert it to a numpy and use a 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 :

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 :

List comprehension:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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