Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a list of tuples based on condition

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'

like image 726
CFD Avatar asked Mar 13 '19 02:03

CFD


People also ask

How do you filter a list based on condition?

You can define any complicated condition on a list element to decide whether to filter it out or not. To do this, create a function (e.g., condition(x) ) that takes one list element as input and returns the Boolean value True if the condition is met or False otherwise.

Can you filter a tuple?

To filter items of a Tuple in Python, call filter() builtin function and pass the filtering function and tuple as arguments. The filtering function should take an argument and return True if the item has to be in the result, or False if the item has to be not in the result.

How do you sort a list of tuples?

If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key.

How do you filter a list in a list Python?

Short answer: To filter a list of lists for a condition on the inner lists, use the list comprehension statement [x for x in list if condition(x)] and replace condition(x) with your filtering condition that returns True to include inner list x , and False otherwise.


2 Answers

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']
>>> 
like image 95
U12-Forward Avatar answered Sep 23 '22 12:09

U12-Forward


try :

In [4]: [x[1] for x in A if x[0] > 2]                                                                                                                                                                           
Out[4]: ['K', 'J']
like image 35
Frank AK Avatar answered Sep 21 '22 12:09

Frank AK