Reputation: 95
I have 2 lists of lists and I want to filter list1 based on matching with elements in list2:
list1 = [[1,2,3], [4,5,16]]
list2 = [[9,8,50], [7,10,3]]
the last element in each list is unique id (example list[0][-1] is unique) I want to get the elements from list1 (list) that have the same last element in elements in list2
In my example
list1[0][-1] is similar to list2[1][-1]
I try this:
[x for x, y in zip(list1, list2) if x[-1] == y[-1]]
but it filter by position (check elements that have the same position in both lists) I want to check them regardless of their position
EDIT expected result:
[1,2,3] from the list 1 (because hit last element (list[-1]) is the same as last element in a list inside list2)
Upvotes: 0
Views: 39
Reputation: 9197
list1 = [[1,2,3], [4,5,16]]
list2 = [[9,8,50], [7,10,3]]
lst = [x for x in list1 if x[-1] in set([y[-1] for y in list2])]
#Out[3]: [[1, 2, 3]]
Upvotes: -1
Reputation: 13393
you can use a set
to first store all the ids from list2
, and then filter list1
using a list comprehension, like this:
list2_ids = {x[-1] for x in list2}
result = [x for x in list1 if x[-1] in list2_ids]
Upvotes: 3