如何在python字典的每个键中计算不同值的平均值? [英] How can I calculate average of different values in each key of python dictionary?
本文介绍了如何在python字典的每个键中计算不同值的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有字典.我想计算每个键的平均值并打印结果,以便结果显示键和相关的平均值.以下代码计算平均值,但我不知道如何将键与平均值关联.我想要的答案是Mean = {22:average1,23:average2,24:average3}.
I have a dictionary. I want to calculate average of values for each key and print result so that the result shows key and associated average. The following code calculates mean but I don't know how to associate key with the average. My desired answer is Mean = {22:average1, 23:average2, 24:average3}.
mydict = {22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]}
Mean =[float(sum(values)) / len(values) for key, values in
mydict.iteritems()]
推荐答案
不要使用列表推导.使用字典理解来计算每个列表的平均值.您也可以<__>来自__future__导入部门,以避免必须使用 float
:
Don't use a list comprehension. Use a dictionary comprehension to calculate the average of each list. You can also from __future__ import division
to avoid having to use float
:
>>> from __future__ import division
>>> d = {22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]}
>>> mean = {k: sum(v) / len(v) for k, v in d.iteritems()}
>>> mean
{22: 0.5, 23: 0.8, 24: 1.8}
这篇关于如何在python字典的每个键中计算不同值的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文