urgeo
urgeo

Reputation: 641

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 (i.e., 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.

Upvotes: 2

Views: 6815

Answers (3)

Ajax1234
Ajax1234

Reputation: 71451

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

Upvotes: 2

jpp
jpp

Reputation: 164663

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

Upvotes: 2

Austin
Austin

Reputation: 26039

Try this:

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

Upvotes: 3

Related Questions