Average tuple of tuples

Issue

How can I average, in a generic sense, the values in a tuple of tuples such that:

(1,2,3),(3,4,5)

becomes:

(2,3,4)

Solution

You can use zip like so:

In [1]: x = ((1, 2, 3), (4, 5, 6))

In [2]: [sum(y) / len(y) for y in zip(*x)]
Out[3]: [2, 3, 4]

Another method using lambda with more then 2 tuples in the tuple and resulting in float’s instead of int’s:

>>> x = ((10, 10, 10), (40, 55, 66), (71, 82, 39), (1, 2, 3))
>>> print tuple(map(lambda y: sum(y) / float(len(y)), zip(*x)))
(30.5, 37.25, 29.5)

Answered By – chown

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published