Python: Compare 2 lists of tuples of different sizes

I have 2 lists of tuples. The first list contains x records with 2 tuples, while the other list contains y (more) records with 3 tuples.

I want to compare both lists, but only the 1st and 2nd elements of the tuples and basically just remove duplicates, but the 3rd record of each tuple in the second list should not be taken into account when comparing.

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 in which all elements from list_y, which also appear in list_x, are deleted. The resulting list should look like this:

[(1,3,65),(2,4,11), ...]

For lists of tuples with the same size, it simply works by simply converting the lists into a set and subtracting both lists:

newlist = list(set(list_y) - set(list_x))

You can also sort the list by the 2nd element of tuples:

newlist.sort(key=lambda tup: tup[1])

: , ?

+4
3

list_x , list_y , list_y , , , . -

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]

-

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)]
+3

:

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])
0
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)]
0
source

Source: https://habr.com/ru/post/1612293/


All Articles