Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding tuple elements in a list

l1=[(2,1),(3,2),(4,5)]
l2=[(2,3),(3,6),(11,3)]

I need:

result=[(2,4),(3,8),(4,5),(11,3)]

using for loop I was able to add tuples having the same first element.

>>> result = []
l1 = [(2, 1), (3, 2), (4, 5)]
l2 = [(2, 3), (3, 6), (11, 3)]
for x, y in l1:
    for p, q in l2:
        if x == p:
            result.append((x, (y + q)))

>>> result
[(2, 4), (3, 8)]

How do I further add (4,5),(11,3)

like image 937
zaolee_dragon Avatar asked Jul 30 '26 19:07

zaolee_dragon


1 Answers

So many ways to achieve the same goal... I like it!

Here is my solution.

l1=[(2,1),(3,2),(4,5)]
l2=[(2,3),(3,6),(11,3)]

d1 = dict(l1)
d2 = dict(l2)
result = []

for k in d1:
    if k in d2:
        result.append((k,d1[k]+d2[k]))
    else:
        result.append((k,d1[k]))

for k in d2:
    if k not in d1:
        result.append((k,d2[k]))


>>>print result
[(2, 4), (3, 8), (4, 5), (11, 3)]
like image 136
alec_djinn Avatar answered Aug 01 '26 10:08

alec_djinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!