We have two lists of tuples of probably different length which look like this:
list1 = [(15339456, 140), (15340320, 412), (15341184, 364), (15342048, 488),
(15342912, 272), (15343776, 350), (15344640, 301), (15345504, 159),
(15346368, 224), (15347232, 241), (15348096, 223), (15348960, 175)]
list2 = [(15339456, 1516), (15341184, 2046), (15342048, 2400), (15342912, 8370),
(15343776, 2112), (15344640, 1441), (15345504, 784), (15346368, 1391)]
The first element of each tuple is the key and is unique in each list. We cannot assume that the key is existing in both lists. One list can have elements with keys that are not in the other. Now we want to sum up the second value of the tuple if its key is in both lists, otherwise we take the complete tuple.
Result:
[(15339456, 1656),
(15340320, 412),
(15341184, 2410),
...
]
Usually lists are summed up using zip
like:
for tup1, tup2 in zip(list1, list2):
sum_ = tup1[1] + tup2[1]
lst.append((tup1[0], sum_))
That would work if both lists were of the same length and each key would exist in both lists, which is not the case.
Is there a nice way to build a condition in this for
loop? Or probably a pythonic solution on this one? Two for
loops and element wise comparing seems not quite satisfying.