Filter a list of tuples based on condition
Asked Answered
B

4

18

I have a list like this:

A=[(1,'A'),(2,'H'),(3,'K'),(4,'J')]

Each member of this list is like this: (number, string)

Now if I want to select the members if the number is bigger than 2 and write the string, what should I do?

For example: selecting the member with a number bigger than 2. the output should be: 'K','J'

Blodgett answered 13/3, 2019 at 2:13 Comment(1)
Does this answer your question? Select value from list of tuples where conditionPirzada
W
20

Use a list comprehension:

[y for x,y in A if x>2]

Demo:

>>> A=[(1,'A'),(2,'H'),(3,'K'),(4,'J')]
>>> [y for x,y in A if x>2]
['K', 'J']
>>> 
Winsor answered 13/3, 2019 at 2:16 Comment(0)
F
7

try :

In [4]: [x[1] for x in A if x[0] > 2]                                                                                                                                                                           
Out[4]: ['K', 'J']
Flem answered 13/3, 2019 at 2:15 Comment(0)
P
5

You want to filter based on some condition, then display a representation of those items. There are a few ways to do this.

List comprehension with filtering. This is usually considered idiomatic or “pythonic”

B = [char for char, val in A if val > 2]

Filter and map. This is lazy and useful if your list is very large and you don’t want to hold it all in memory at once.

greater_than_2 = filter(lambda a: a[1] > 2, A)
B = map(lambda a: a[0], greater_than_2)

Or a loop and accumulator. This is good if you have side effects you want to do for each element.

B = []
for char, val in A:
    if val > 2:
        B.append(char)
Presidentelect answered 13/3, 2019 at 2:25 Comment(0)
E
1

This solution uses map, filter and lambda functions to make it work. But it might be confusing for some. However, it is faster than list comprehension.

list(map(lambda x: x[1], filter(lambda x: x[0]>2, A)))

In short, first the filter function filters out the tuples in A where the first element is greater than 2. Then we take this filtered list and apply a mapping with another lambda function to select only the 2nd element (character). The result is as desired:

['K', 'J']

Another tool to be aware of is the compress tool from itertools, which is also faster than list comprehension. But it returns tuples, so you need to use another map to get only character elements.

from itertools import compress
list(compress(A, map(lambda x: x[0]>2, A)))
Out: [(3, 'K'), (4, 'J')]
Exceptional answered 23/8, 2022 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.