在python中平均一个dictinary

时间:2015-10-20 18:12:47

标签: python dictionary average

我的字典正在从.CSV文件读取到python中,但是我需要对该字典中的分数进行平均。

Classopen = open("Student" + "class" + str(classes) + ".csv","rb")
Classfile = csv.reader(Classopen)
Classdict = {}

for people in Classfile:
    students = people[0]
    studentvalue = str(people[1])
    if students in Classdict:
        Classdict[students].append(people)
    else :
        Classdict[students] = [studentvalue]

由于

1 个答案:

答案 0 :(得分:0)

只需计算每个学生的所有值的总和,然后分成值的计数:

for student in classdict:
    sum(map(int, classdict[student])) / float(len(classdict[student]))

如果您执行studentvalue = int(people[1])而不是studentvalue = str(people[1]),那就更简单了:

for student in classdict:
    print("{} - {}".format(student, sum(classdict[student]) / float(len(classdict[student]))))