17
votes

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!

2
Your solution works for me if I fix the constructors for the lists. (Hint: use [5,8] instead of list(5,8)) - Kevin

2 Answers

26
votes

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

3
votes

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)