Python: filter list of list with another list

43,800

Solution 1

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

Solution 2

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)
Share:
43,800

Related videos on Youtube

fj123x
Author by

fj123x

Updated on July 09, 2022

Comments

  • fj123x
    fj123x almost 2 years

    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!

    • Kevin
      Kevin over 10 years
      Your solution works for me if I fix the constructors for the lists. (Hint: use [5,8] instead of list(5,8))
  • Danica
    Danica over 10 years
    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.
  • Admin
    Admin over 10 years
    @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...
  • Tom N Tech
    Tom N Tech almost 4 years
    A more generic approach is to intersect the two lists.
  • Ashwini Chaudhary
    Ashwini Chaudhary almost 4 years
    @rjurney If you mean by using sets, then depends, do you want to lose order or preserve it? And thanks for the useful downvote.