2

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.

urgeo
  • 645
  • 1
  • 9
  • 19

3 Answers3

3

Try this:

B = [x for x in A if x[1] <= 30]
Austin
  • 25,759
  • 4
  • 25
  • 48
2

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))
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2

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]])
jpp
  • 159,742
  • 34
  • 281
  • 339