29

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!

1
  • 1
    Your solution works for me if I fix the constructors for the lists. (Hint: use [5,8] instead of list(5,8)) Commented Aug 26, 2013 at 16:20

2 Answers 2

42

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

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

3 Comments

A more generic approach is to intersect the two lists.
@rjurney If you mean by using sets, then depends, do you want to lose order or preserve it? And thanks for the useful downvote.
It's often worth using a set for list_b: set_b=set(list_b); result = [x for x in list_a if x[0] in set_b], on account of faster lookups + deduping the list. And there's no impact to ordering
5

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)

2 Comments

Your comment about making the function beforehand is mistaken: filter(lambda list_a: ..., list_a) would do exactly the same thing, since the lambda statement is evaluated down to a function value before being passed to filter.
@Dougal - Thank you. I did that because, a while back, someone got on me saying it re-created the lambda each time. I thought that sounded wrong, but assumed he knew more than me and thus went with his advice. Shows what you get for not double-checking info...

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.