简体   繁体   English

从Python中每个元组的第二个值计算平均和

[英]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.

相关问题 汇总列表中每个元组的第二个值 - Sum the second value of each tuple in a list 使用Python为元组中每个给定的第一个值求和的元组中的第二个值 - Sum second value in tuple for each given first value in tuples using Python 按第二个值(或按和)对“元组”进行排序 - Sorting a “Tuple” by the second value (or by sum) Python list_of_tuples:每个元组的第二个val,仅当元组的第一个val == - Python list_of_tuples: sum second val of each tuple, only if first val of tuple == something 如何为两列中的每个唯一值计算 Python 中的加权平均值? - How to calculate a weighted average in Python for each unique value in two columns? 在python中计算每个用户的平均值 - calculate the average of each user in python Python 将元组的第二个元素与第一个元素相加 - Python Sum Second Element of Tuple by First Element Python - 元组中的重复(第二个)值 - Python - Repeated (second)) value in tuple 如何为每个地区的每一年做一个堆积条形图来计算 Quantity_Sold 的总和(或平均值)? Python - How to do a Stacked Barplot for each Year per Region to calculate the sum(or average) of Quantity_Sold? Python 如何在不使用 sum() 的情况下从每个键中有多个值的字典中的平均值计算平均值? - How do I calculate an average from averages in a dictionary with multiple values in each key without using sum()?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM