3

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]]
1
  • Note that you can spell set([a,b,c]) as the set literal {a,b,c}, mirroring the normal mathematical notation for sets. Commented Dec 9, 2015 at 15:14

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.