[英]calculating the mean of numeric values in a list of tuples
我是 Python 新手,偶然发现了以下问题:我有两个列表(listA 和 listB)由元组('str',float)组成,我必须计算每个列表的浮点值的平均值。
groups = ['A', 'B', 'B', 'A', 'B', 'B', 'B', 'B', 'A', 'A']
scores = [0.2, 0.3, 0.9, 1.1, 2.2, 2.9, 0.0, 0.7, 1.3, 0.3]
list_groups_scores = list(zip(groups,scores))
list_groups_scores.sort()
print(list_groups_scores)
listA = list_groups_scores[0:4]
listB = list_groups_scores[5:9]
print(listA, listB)
任何人都可以帮忙吗? 非常感谢!
使用 dict 来保存组和分数
from collections import defaultdict
groups = ['A', 'B', 'B', 'A', 'B', 'B', 'B', 'B', 'A', 'A','K']
scores = [0.2, 0.3, 0.9, 1.1, 2.2, 2.9, 0.0, 0.7, 1.3, 0.3,1]
data = defaultdict(list)
for g,s in zip(groups,scores):
data[g].append(s)
for grp,scores in data.items():
print(f'{grp} --> {sum(scores)/len(scores)}')
输出
A --> 0.725
B --> 1.1666666666666667
K --> 1.0
两个不同的点,每个点都有几个解决方案。
一、如何从列表中的元组中取回浮点数
使用解包习语和列表理解
float_list = [v for i, v in listA]
纯Python
float_list = [] for item in listA: float_list.append(item[1])
二、 如何计算平均值
从某个模块导入mean
from Numpy import mean
from statistics import mean
使用sum
和length
对列表中的值求和并除以列表长度
mean = sum(v in a_list) / len(a_list)
纯Python
循环聚合值并计数到长度
aggregate = 0 length = 0 for item in a_list: aggregate += item length += 1 mean = aggregate / length
注意:选择aggregate
有两个原因:
- avoiding the use of a built-in function - generalizing the name of the variable, for example, a function other than addition could be used.
解决方案
解决方案可以是步骤 I 和步骤 II 的混合,但临时解决方案可以省去中间列表的构建(第 I 部分示例中的float_list
)
例如:
使用sum
和length
对列表中的解压缩值求和并除以列表长度
mean = sum(v in float_list) / len(float_list)
注意: v in float_list
中的v in float_list
不会创建列表; 它是一个发电机,可按需提供花车。
纯Python
循环聚合值并计数到长度
aggregate = 0 length = 0 for item in listA: aggregate += item[1] length += 1 mean = aggregate / length
试试下面的代码:
sum = 0
ii=0
for sub in listA:
ii+=1
i=sub[1]
sum = sum + i
avg=sum/ii
s = lambda x:[i[1] for i in x]
print(sum(s(listA))/len(listA))
print(sum(s(listB))/len(listB))
python中有一种特殊类型的循环,看起来像这样。
listANumbers = [i[1] for i in listA]
它遍历 listA 中的每个元素并将每个元素 [1] 设置为一个新列表。
结果:
[0.2, 0.3, 1.1, 1.3]
然后,您可以取新列表的总和和平均值。
listANumbers = [i[1] for i in listA]
meanA = sum(listANumbers) / len(listANumbers)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.