Average tuple of tuples

19,979

Solution 1

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)

Solution 2

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

from numpy import mean  # or write your own mean function
tuple(map(mean, zip(*x)))
# (2.0, 3.0, 4.0)

or:

from numpy import mean
tuple(mean(x, axis=0))
Share:
19,979

Related videos on Youtube

Baz
Author by

Baz

Updated on September 16, 2022

Comments

  • Baz
    Baz over 1 year

    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)
    
  • David Robinson
    David Robinson over 11 years
    The OP mentions that the input is a "tuple of tuples", so there could be more than 2.
  • David Robinson
    David Robinson over 11 years
    @Avaris: Thanks- great idea (added), though you would have to turn it to a tuple afterwards.
  • l4mpi
    l4mpi over 11 years
    please don't recommend numpy without mentioning that it is not part of the standard library and has c extensions.
  • David Robinson
    David Robinson over 11 years
    @l4mpi: Like I said, he could also write his own mean function.
  • l4mpi
    l4mpi over 11 years
    Ah sorry, didn't read the comment. I just happen to see numpy get recommended very often for tasks where it would only be a good choice if the program already uses numpy or the input data is huge (which it doesn't seem to be in this case), without mentioning the fact that you have to install and compile it...
  • Baz
    Baz over 2 years
    This is a python question.