5

Here's my list of tuples:

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

I'm trying to sum the first index value in a list of tuples where the values at indices 1 and 2 are identical. Note that regions[0] and regions[3] have the same values at indices 1 and 2.

My desired list is:

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

I realize that I probably need to save it as a dictionary first, probably with the second value as the first key and the third value as the second key and summing if it already exists. Just wondering if there's a better or easier way: I'm thinking maybe using some intersect function.

1
  • 2
    Does the ordering of tuples in the result matter? Commented Apr 11, 2013 at 16:05

1 Answer 1

6
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 isn't a built-in function to do this; it's far too specialized a task.

Sign up to request clarification or add additional context in comments.

4 Comments

Beat me to it - and more completely :)
and is .iteritems() better/different than .items()?
.iteritems() is for Python 2 and I believe returns a generator. In Python 3 .iteritems() does not exist. @bozdoz
you could drop (). A tuple is created by a comma (,): for a, b, c in regions: results[b,c] += a. You could also unpack in the for-loop: result = [(a, b, c) for (b, c), a in sums.items()]. Or result = [(a,) + t for t, a in sums.items()]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.