huang06
huang06

Reputation: 167

How to combine tuples with the same key value when combine lists

I'm trying to combine multiple lists into one list, the values with the same tuple key must been add together.

For example:

A = [ (1,2),(5,2) ]
B = [ (1,2),(5,5),(11,2) ]

Expected result:

result = [ (1,4),(5,7),(11,2) ]

Upvotes: 1

Views: 1176

Answers (2)

Akavall
Akavall

Reputation: 86266

If the order is not important, using collections.Counter is another option:

In [21]: from collections import Counter

In [22]: A = [ (1,2),(5,2) ]

In [23]: B = [ (1,2),(5,5),(11,2) ]

In [24]: (Counter(dict(A)) + Counter(dict(B))).items() # list(...) for Python 3
Out[24]: [(1, 4), (11, 2), (5, 7)]

Upvotes: 1

chthonicdaemon
chthonicdaemon

Reputation: 19800

You can do this quite simply once you realise the idea of keeping track of the first element is done well with a dict

c = dict(A)
for key, value in B:
    c[key] = c.get(key, 0) + value

result = list(c.items())

Upvotes: 3

Related Questions