Reputation: 93
I have 2 lists of tuples. The first list contains x entries with 2-tuples while the other list contains y (more) entries with 3-tuples.
I want to compare both lists, but only the 1st and 2nd element of the tuples and basically just remove dublicates, but the 3rd entry of every tuple in the 2nd list should be not considered during the comparison.
list_x=[(1,1),(1,2),(2,3),(2,5),(4,6), ...]
list_y=[(1,1,33),(1,3,65),(2,4,11), ...]
Now I want to create a new list where all elements from list_y which also occur in list_x are removed. The resulting list should look like this:
[(1,3,65),(2,4,11), ...]
For lists of tuples with the same size it works simply by just converting the lists to a set and subtract both lists:
newlist = list(set(list_y) - set(list_x))
it is also possible to sort the resulting list by the 2nd element of the tuples:
newlist.sort(key=lambda tup: tup[1])
But now the question is: how is it possible to do this if the lists look like above?
Upvotes: 4
Views: 1312
Reputation: 90889
You can convert list_x
to a set, and then loop over list_y
and check if the first two elements of list_y
are present in the set or not, if not present include them in the resultant list, and this can be done in a list comprehension as given below. Example -
list_x=[(1,1),(1,2),(2,3),(2,5),(4,6), ...]
list_y=[(1,1,33),(1,3,65),(2,4,11), ...]
list_x_set = set(list_x)
result = [item for item in list_y if item[0:2] not in list_x_set]
Demo -
In [57]: list_x=[(1,1),(1,2),(2,3),(2,5),(4,6)]
In [58]: list_y=[(1,1,33),(1,3,65),(2,4,11)]
In [59]: list_x_set = set(list_x)
In [60]: result = [item for item in list_y if item[0:2] not in list_x_set]
In [62]: result
Out[62]: [(1, 3, 65), (2, 4, 11)]
Upvotes: 3
Reputation: 113915
Try the following code:
set_x = set(list_x)
answer = sorted([t for t in list_y if (t[0], t[1]) not in set_x], key=lambda t:t[1])
Upvotes: 0
Reputation: 5658
with for loops
list_x=[(1,1),(1,2),(2,3),(2,5),(4,6)]
list_y=[(1,1,33),(1,3,65),(2,4,11)]
for elx in list_x:
for ely in list_y:
if ely[:-1] == elx:
list_y.remove(ely)
print(list_y)
[(1, 3, 65), (2, 4, 11)]
Upvotes: 0