Python: filter list of list with another list
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!
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
You are actually very close. Just do this:
list_a = list(
list(1, ...),
list(5, ...),
list(8, ...),
list(14, ...)
)
# Fix the syntax here
list_b = [5, 8]
return filter(lambda list_a: list_a[0] in list_b, list_a)