Average tuple of tuples

蓝咒 提交于 2020-07-07 11:57:27

问题


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)

回答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)



回答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))


来源:https://stackoverflow.com/questions/12412546/average-tuple-of-tuples

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!