steve9120
steve9120

Reputation: 19

Python - Adding elements of a tuple in a list

How do I add elements of a tuple in a list?

[(0.50421782178217822, 0.4822060104027705), (0.4375, 0.6666666666666666), (0.375, 0.4642857142857143), (0.26666666666666666, 0.16666666666666666)]

For example:

=> 0.50421... + 0.4375 + ... => 0.4822... + 0.666 + ...

It should return a tuple.

For example, (0th element sum, 1st element sum).

The thing that's bothering is the square brackets.

I'm stuck here, but don't know how to add the tuples.

[(x,y) for (x,y) in dict.itervalues()]

Upvotes: 1

Views: 224

Answers (3)

Kenneth Goodman
Kenneth Goodman

Reputation: 86

If functional programming isn't your thing, I decided to give another answer.

What we can do is treat the problem as two different problems. Sum the first entry of each tuple and sum the second entry in each tuple. Then combine them into one tuple. Ok, that doesn't sound too bad.

Lets start with just summing a list of 1-tuples, well that is just a list. Summing that is easy.

>>> aList = [1,2,3,4,5]
>>> theSum = sum(aList)
>>> print(theSum)
15

Well that wasn't too bad, makes sense.

Now if we had a list of 2-tuples (or n-tuples for that matter) and only wanted the sum of the first entries. Well we could just ignore the rest of the entries as we sum.

>>> aList = [(1,10),(2,10),(3,10),(4,10),(5,10)]
>>> theSum = sum([firstEntry for firstEntry,secondEntry in aList])
>>> print(theSum)
15

Not too bad. Now if want to make this a bit more clear we can just clean the second line up.

>>> theSum = sum(firstEntry for firstEntry,_ in aList)

What I have done is taken out the brackets and put an underscore for the unused method. This was someone reading the code can see that it is obvious that we don't care about the second item.

Now what is going on here, what we are doing is do a regular 'for in' loop but our variable is now a name tuple itself, pretty convenient.

For the answer to the problem

>>> aList = [(0.50421782178217822, 0.4822060104027705), (0.4375, 0.6666666666666666), (0.375, 0.4642857142857143), (0.26666666666666666, 0.16666666666666666)]
>>> theSum = (sum(firstEntry for firstEntry,_ in aList),sum(secondEntry for _,secondEntry in aList))
>>> print(theSum)
(1.5833844884488448, 1.779825058021818)

And we are done.

Upvotes: 1

Stefan Pochmann
Stefan Pochmann

Reputation: 28596

>>> map(sum, zip(*mylist))
[1.5833844884488448, 1.779825058021818]

Upvotes: 5

Garrett R
Garrett R

Reputation: 2662

You can do it with the built-in reduce function.

myList = [(0.50421782178217822, 0.4822060104027705), (0.4375, 0.6666666666666666), (0.375, 0.4642857142857143), (0.26666666666666666, 0.16666666666666666)]
reduce(lambda x,y: (x[0]+y[0], x[1]+y[1]), myList)

(1.5833844884488448, 1.779825058021818)

Or with two aggregation variables.

s1,s2 = 0.0, 0.0
for x,y in myList:
   s1+=x
   s2+=y

Upvotes: 1

Related Questions