Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove duplicate value from list of tuples based on values from another list

I have 2 lists similar to these:

l1 = [('zero', 0),('one', 2),('two', 3),('three', 3),('four', 5)]
l2 = [('zero', 0),('one', 3),('four', 2),('ten', 3),('twelve', 8)]

I want to compare the lists and

  1. remove duplicates from both if both values are the same
  2. if the first value is a match remove the tuple from the list where the second value is lower

I can do the first with

l3 = [(a,b) for (a,b) in l1 if (a,b) not in l2]
l4 = [(a,b) for (a,b) in l2 if (a,b) not in l1]

or using set though it doesn't preserve order

l3 = set(l1) - set(l2)

but I'm having a hard time figuring out the second. I tried to start with removing based on just the first value with

l3 = [(a,b) for (a,b) in l1 if a not in l2]

but that doesn't work. My desired output for l3 & l4 is:

l3
[('two', 3),('three', 3),('four', 5)]

l4
[('one', 3),('ten', 3),('twelve', 8)]

Any guidance would be appreciated.

like image 209
nebulousman Avatar asked Dec 11 '20 21:12

nebulousman


Video Answer


1 Answers

You could do:

d1 = dict(l1)
d2 = dict(l2)

l3 = [(k, v) for k, v in d1.items() if k not in d2 or d2[k] < v]
l4 = [(k, v) for k, v in d2.items() if k not in d1 or d1[k] < v]

print(l3)
print(l4)

Output

[('two', 3), ('three', 3), ('four', 5)]
[('one', 3), ('ten', 3), ('twelve', 8)]

The idea is to use dictionaries for fast lookups of matching first values, if any, and then check if the corresponding second value is less to the one in the current list.

like image 193
Dani Mesejo Avatar answered Oct 26 '22 11:10

Dani Mesejo