Johannes
Johannes

Reputation: 1064

Filter Python list of lists by another list

How can I filter a list of lists based on another list/set in python. For a simple list this can be done as:

mylist = [1,2,3,4,5,3,5,2,3,2,7,5,3]
[x for x in mylist if x in {3,5}]

But how to do that for a list of lists most efficiently:

mylistoflists = [[], [5, 1, 6], [5, 1, 6, 2, 7], [5, 1, 6, 2, 7, 4, 8], [5, 1, 11, 10], [5, 1, 4, 11, 10, 12]]
myvalues = set([4,10])

The results should still be a list of lists like following:

 [[], [], [], [4], [10], [4, 10]]

Upvotes: 3

Views: 217

Answers (2)

Kasravnd
Kasravnd

Reputation: 107287

If You don't care about the intersection order as a more pythonic way you can use set.intersection within a list comprehension:

>>> new = [list(myvalues.intersection(i)) for i in mylistoflists]
>>> new
[[], [], [], [4], [10], [10, 4]]

Upvotes: 3

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

Basically, the same idea:

>>> mylistoflists = [[], [5, 1, 6], [5, 1, 6, 2, 7], [5, 1, 6, 2, 7, 4, 8], [5, 1, 11, 10], [5, 1, 4, 11, 10, 12]]
>>> myvalues = {4, 10}
>>> [[x for x in L if x in myvalues] for L in mylistoflists]
[[], [], [], [4], [10], [4, 10]]

If myvalues is a constant, you can replace it with a set literal in the list comprehension for better performance.

Upvotes: 5

Related Questions