[英]calculate average sum from second value of each tuple in python
I used this here to sum the second value of each tuple in a list: https://stackoverflow.com/a/12218119/9195816 我在这里使用它来求和列表中每个元组的第二个值: https : //stackoverflow.com/a/12218119/9195816
sum(n for _, n in structure)
works fine. sum(n for _, n in structure)
工作正常。 But i dont need the sum, i only need the average. 但是我不需要总和,我只需要平均值。 So something like
sum(n for _, n in structure) \\ total_amount_of_values
. 所以像
sum(n for _, n in structure) \\ total_amount_of_values
。 But of course, this won't work: 但是,当然,这是行不通的:
TypeError: unsupported operand type(s) for /: 'float' and 'list'
TypeError:/不支持的操作数类型:“ float”和“ list”
My list looks ie like this: [1000, 900.84, 500, 1240.11] 我的列表看起来像这样:[1000,900.84,500,1240.11]
n = [1000, 900.84, 500, 1240.11]
average = sum(n)/len(n)
This will give you the average of the list n
这将为您提供列表
n
的平均值
But it sounds like your list looks more like this 但是听起来您的列表看起来更像这样
n = [(a,b), (c,d), ...]
and you want 而你想要
b + d + ... / len(n)
If this is the case, then you can do this like so 如果是这种情况,那么您可以这样做
average = sum(map(lambda x: x[1], n)) / len(n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.