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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With