元组的平均元组 [英] Average tuple of tuples

查看:33
本文介绍了元组的平均元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从一般意义上来说,我如何平均一个元组中的值,使得:

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

变成:

(2,3,4)

解决方案

您可以使用 zip 像这样:

在[1]中:x = ((1, 2, 3), (4, 5, 6))在 [2] 中:[sum(y)/len(y) for y in zip(*x)]输出[3]:[2, 3, 4]

<小时>

另一种使用 lambda 的方法,元组中有超过 2 个元组,结果是浮点数而不是整数:

<预><代码>>>>x = ((10, 10, 10), (40, 55, 66), (71, 82, 39), (1, 2, 3))>>>打印元组(map(lambda y: sum(y)/float(len(y)), zip(*x)))(30.5, 37.25, 29.5)

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)

解决方案

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)

这篇关于元组的平均元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆