0
votes

I have 2 lists of lists and my code can filter list1 based on matching with elements in list2: Means return lists inside list1 which shares the same last element with any list inside list2

list1 = [[1,2,3], [4,5,16], [9, 0, 50]]
list2 = [[9,8,50], [7,10,3]]

list2_ids = {x[-1] for x in list2}
result = [x for x in list1 if x[-1] in list2_ids]

#result
[1,2,3]
[9, 0, 50]

I want to group the filtered lists from list1 to to groups based on their first element if their share the same last element with another list in list2 AND share the first element too.

from my example:

lists_with_shared_first_and_last_element = [9, 0, 50]
lists_with_shared_last_element_and_different_first = [1,2,3]
1
so if I'm understanding correctly... you want all lists in list1 where the first and last values occur in a list from list2?M Z
from the collecting lists which share the last elements, I want to specify which are have the same first element, and which have different first elementRavanelli

1 Answers

1
votes

You seem to be very close:

With list comprehension because OP asked for it:

list1 = [[1,2,3], [4,5,16], [9, 0, 50]]
list2 = [[9,8,50], [7,10,3]]

list2_ids = {(x[0], x[-1]) for x in list2}
for x in list2: list2_ids.add(x[-1])

lists_with_shared_first_and_last_element = [x for x in list1 if (x[0], x[-1]) in list2_ids]
lists_with_shared_last_element_and_different_first = [x for x in list1 if x[-1] in list2_ids and (x[0], x[-1]) not in list2_ids]

# same results.........