[英]How can I calculate average of different values in each key of python dictionary?
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}.
我想要的答案是 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()]
You were on the right track.你走在正确的轨道上。 You just needed a dictionary comprehension instead of a list comp.
你只需要一个字典理解而不是一个列表组合。
_dict = {22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]}
mean = {key : float(sum(values)) / len(values) for key, values in _dict.iteritems()}
print(mean)
{22: 0.5, 23: 0.8, 24: 1.8}
Notes:笔记:
.iteritems
is replaced with .items
in python3 .iteritems
替换.items
在python3dict
as a variable name, it shadows the builtin class with the same name. dict
作为变量名,它会掩盖具有相同名称的内置类。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
以避免必须使用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}
Update for Python 3.4+更新 Python 3.4+
>>> from statistics import mean # Python 3.4+
>>> d = {22: [1, 0, 0, 1], 23: [0, 1, 2, 1, 0], 24: [3, 3, 2, 1, 0]}
>>> {k:mean(v) for k,v in d.items()}
{22: 0.5, 23: 0.8, 24: 1.8}
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.