gpt4 book ai didi

python - 在 Python 中平均一个字典列表

转载 作者:太空宇宙 更新时间:2023-11-04 09:00:48 25 4
gpt4 key购买 nike

我有一个每日值列表,按如下顺序排列到一个字典列表中:

vals = [
{'date': '1-1-2014', 'a': 10, 'b': 33.5, 'c': 82, 'notes': 'high repeat rate'},
{'date': '2-1-2014', 'a': 5, 'b': 11.43, 'c': 182, 'notes': 'normal operations'},
{'date': '3-1-2014', 'a': 0, 'b': 0.5, 'c': 2, 'notes': 'high failure rate'},
...]

我想做的是获得当月 a、b 和 c 的平均值。

有没有比做这样的事情更好的方法:

val_points = {}
val_len = len(vals)

for day in vals:
for p in ['a', 'b', 'c']:
if val_points.has_key(p):
val_points += day[p]
else:
val_points = day[p]

val_avg = dict([(i, val_points[i] / val_len] for p in val_points])

我没有运行上面的代码,可能有问题,但我希望我能理解这个想法。我知道使用运算符、itertools 和集合的某种组合可能有更好的方法。

最佳答案

{p:sum(map(lambda x:x[p],vals))/len(vals) for p in ['a','b','c']}

输出:

{'a': 5, 'c': 88, 'b': 15.143333333333333}

关于python - 在 Python 中平均一个字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25661580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com