Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array to show rows with a specific value in a specific column

Tags:

python

list

Let's say i have a multidimensional list l:

l = [['a', 1],['b', 2],['c', 3],['a', 4]]

and I want to return another list consisting only of the rows that has 'a' in their first list element:

m = [['a', 1],['a', 4]]

What's a good and efficient way of doing this?

like image 386
c00kiemonster Avatar asked Jan 14 '10 05:01

c00kiemonster


1 Answers

Definitely a case for a list comprehension:

m = [row for row in l if 'a' in row[0]]

Here I'm taking your "having 'a' in the first element" literally, whence the use of the in operator. If you want to restrict this to "having 'a' as the first element" (a very different thing from what you actually wrote!-), then

m = [row for row in l if 'a' == row[0]]

is more like it;-).

like image 136
Alex Martelli Avatar answered Oct 21 '22 07:10

Alex Martelli