Sum of tuples if identical values

Here is my list of tuples:

regions = [(23.4, 12, 12341234), 
           (342.23, 19, 12341234), 
           (4312.3, 12, 12551234), 
           (234.2, 12, 12341234)]

I am trying to summarize the first index value in a list of tuples, where the values ​​from indices 1 and 2 are identical. Note that areas [0] and areas [3] have the same values ​​at indices 1 and 2.

My desired list:

result = [(257.6, 12, 12341234), 
          (342.23, 19, 12341234), 
          (4312.3, 12, 12551234)]

I understand that I probably need to save it first as a dictionary, possibly with a second value as the first key and a third value as the second key and summing if it already exists. Just wondering if there is a better or simpler way: I think, perhaps using some intersection function.

+5
source share
1 answer
from collections import defaultdict

sums = defaultdict(float)
for c, a, b in regions:
    sums[a, b] += c
result = [(csum, a, b) for (a, b), csum in sums.iteritems()]

There is no built-in function for this; This is too specialized a task.

+6
source

All Articles