Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: filter list of list with another list

Tags:

i'm trying to filter a list, i want to extract from a list A (is a list of lists), the elements what matches they key index 0, with another list B what has a serie of values

like this

list_a = list(   list(1, ...),   list(5, ...),   list(8, ...),   list(14, ...) )  list_b = list(5, 8)  return filter(lambda list_a: list_a[0] in list_b, list_a) 

should return:

list(     list(5, ...),     list(8, ...) ) 

How can i do this? Thanks!

like image 283
fj123x Avatar asked Aug 26 '13 16:08

fj123x


People also ask

How do I filter a list from one list to another in Python?

Python has a built-in function called filter() that allows you to filter a list (or a tuple) in a more beautiful way. The filter() function iterates over the elements of the list and applies the fn() function to each element. It returns an iterator for the elements where the fn() returns True .

Can a list contains another list in Python?

Now, we can see how to Check if a list contain another list in Python. In this example, I have taken a variable as a list, and the if condition is used to check. If the check_list =[“orange”] is present in the list then it returns “List is present” else “List is not present”.

How do you filter an array of objects in Python?

You can select attributes of a class using the dot notation. Suppose arr is an array of ProjectFile objects. Now you filter for SomeCocoapod using. NB: This returns a filter object, which is a generator.


1 Answers

Use a list comprehension:

result = [x for x in list_a if x[0] in list_b] 

For improved performance convert list_b to a set first.

As @kevin noted in comments something like list(5,8)(unless it's not a pseudo-code) is invalid and you'll get an error.

list() accepts only one item and that item should be iterable/iterator

like image 200
Ashwini Chaudhary Avatar answered Oct 16 '22 00:10

Ashwini Chaudhary