zaolee_dragon
zaolee_dragon

Reputation: 109

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)

Upvotes: 3

Views: 117

Answers (4)

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

It can be easily done by using dict formed with l1 and iterating over l2, see working code snippet below:

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

for y in l2:
    result[y[0]] = result.get(y[0],0) + y[1]

result = result.items()
print result #[(11, 3), (2, 4), (3, 8), (4, 5)]

Or simply build results by iterating over concatenation of l1 and l2:

l1=[(2,1),(3,2),(4,5)]
l2=[(2,3),(3,6),(11,3)]
result = {}
for item in l1 + l2:
    result[item[0]] = result.get(item[0],0) + item[1]

Good luck!

Upvotes: 2

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160417

There's no need to go through the elements of l2 for all elements of l1 if I understand what you're going for. Just use zip (or izip_longest if the lists have an uneven size) to use a tuple from each list and then append the first item and the sum if the first item matches and extend both tuples if they don't:

for tup1, tup2 in zip(l1, l2):
    if tup1[0] == tup2[0]:
        result.append((tup1[0], (tup1[1] + tup2[1])))
    else:
        result.extend([tup1, tup2])

With your input, this returns the required output:

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

Upvotes: 2

alec_djinn
alec_djinn

Reputation: 10789

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

Upvotes: 2

kfx
kfx

Reputation: 8537

Seems natural to use a dictionary to keep track of which keys are already used. You can reduce the code size by using defaultdict:

import collections

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

d = collections.defaultdict(int)
for x,y in l1 + l2:
    d[x] += y
print sorted(d.items())

Upvotes: 1

Related Questions