开发者

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

开发者 https://www.devze.com 2022-12-16 03:34 出处:网络
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开发者_如何转开发

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?


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


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


With the filter function:

m = filter(lambda x: x[0] == 'a', l)

or as a list comprehension:

m = [x for x in l where x[0] == 'a']


What's wrong with just:

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

Or:

m = filter(lambda x: x[0] == 'a', l)

I doubt the difference between these will be significant performance-wise. Use whichever is most convenient. I don't like lambdas, but the filter can be replaced with itertools.ifilter for larger lists if that's a problem, but you can also change the list comprehension to a generator (change the [] to ()) to achieve the same general result. Other than that, they're probably identical.


[i for i in l if i[0]=='a']

btw, take a look at Python's list comprehension with conditions.

0

精彩评论

暂无评论...
验证码 换一张
取 消