Python 3.4-如何获取字典值的平均值? [英] Python 3.4 - How to get the average of dictionary values?
问题描述
我有以下字典:
StudentGrades = {
'Ivan': [4.32, 3, 2],
'Martin': [3.45, 5, 6],
'Stoyan': [2, 5.67, 4],
'Vladimir': [5.63, 4.67, 6]
}
我想创建一个函数,以打印学生的平均成绩,即值的平均值,但是我不知道如何.你能帮我吗?
I want to make a function that prints the average of the grades of the students, i.e. the average of the values, but I have no idea how. Can you help me please?
推荐答案
此答案适用于Python2,即已死
好的,所以让我们遍历所有字典键并对项目取平均值:
Okay, so let's iterate over all dictionary keys and average the items:
avgDict = {}
for k,v in StudentGrades.iteritems():
# v is the list of grades for student k
avgDict[k] = sum(v)/ float(len(v))
在Python3中,不再需要
iteritems()
方法,可以直接使用items()
.
In Python3, the
iteritems()
method is no longer necessary, can useitems()
directly.
现在您可以看到:
avgDict
Out[5]:
{'Ivan': 3.106666666666667,
'Martin': 4.816666666666666,
'Stoyan': 3.89,
'Vladimir': 5.433333333333334}
从您的问题来看,我认为您对字典的迭代感到不满意,因此输出与列表相同:
From your question I think you're queasy about iteration over dicts, so here is the same with output as a list :
avgList = []
for k,v in StudentGrades.iteritems():
# v is the list of grades for student k
avgDict.append(sum(v)/ float(len(v)))
但是要小心:不能保证在字典中的项目顺序;这就是说,不能保证在字典上打印或迭代时键/值的顺序(因为字典是未排序的"). 虽然可以保证在相同的相同字典对象(无添加/删除)上循环两次,但它们的行为相同.
Be careful though : the order of items in a dictionary is NOT guaranteed; this is, the order of key/values when printing or iterating on the dictionary is not guaranteed (as dicts are "unsorted"). Looping over the same identical dictionary object(with no additions/removals) twice is guaranteed to behave identically though.
这篇关于Python 3.4-如何获取字典值的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!