我需要知道如何使用多个分数的学生平均分数在python上排序我的字典?

时间:2015-01-27 14:17:42

标签: python sorting dictionary average

我班上有几十名学生参加了测验。我花了不止一个,我想用python计算平均值。我将分数保存在一个文本文件中,但我不知道如何编程,所以它按总分除以它们在那里测试的次数进行排序。即时通讯使用python 3.4.1。

the text file looks like this : 
zor:10
zor:21
bob:30
qwerty:46

我试图按此分类:

 if schClass == '2':
     schClass = open("scores2.txt", 'r')
     li = open("scores2.txt", 'r')
     data = li.read().splitlines()
     for li in data:
        name = li.split(":")[0]
        score = li.split(":")[1]
        if name not in diction1:
            diction1[name] = score
        elif name in diction1  :
            diction1[name] = (score) + (diction1[name])
            for name in diction1:
                diction1[name] = int(diction1[name])/3

2 个答案:

答案 0 :(得分:0)

您可以使字典具有以下结构:

diction1 = {'zor': [10, 21,], 'bob': [30]} 

然后创建一个新的字典,用于存储名称和平均分数:

averages_dct = {'zor': 15.5, }

您的代码应如下所示:

diction1 = {'john': [10, 20], 'mary': [12,], 'chris': [10, 20]}

# Contains names as keys and average as values.
averages_dct = {}

for name in diction1:
    student_average = sum(diction1[name]) / len(diction1[name])

    # Store the value:
    averages_dct.update({name: student_average})


# Dict containing averages as keys and names as values
# (inserting averages first)
reversed_dct = {averages_dct[k]: [] for k in averages_dct}

# (matching names)
for average in reversed_dct:
    for name in averages_dct:
        if average == averages_dct[name]:

            # Adds name of student if he has this average
            reversed_dct[average].append(name)

# Prints the results from highest to lowest.
for av in sorted(reversed_dct, reverse=True):
    print('average: %s, students: %s' % (av, reversed_dct[av]))

答案 1 :(得分:0)

这可以帮到你吗?

def dataload():
#This is just to load your data into a custom dictionary, for simplicity
#i wrote example data into a string, you can use your I/O logic 
    test="zor:10\n\
zor:21\n\
bob:30\n\
qwerty:46\n\
zor:24"
    dictionary = {}
    d = test.splitlines()
    for i in d:
        values = i.split(':')
        name  = values[0]
        score = float(values[1])
        if name not in dictionary:
            dictionary[name] = [score]
        else:
            l = dictionary[name]
            l.append(score)            
            dictionary[name] = l
    return dictionary


def printdictionary(d):
#This is shows the content of your custom dictionary
    for item in d.keys():
        l = d[item]
        avg = 0
        for exam in l:
            avg = avg + exam
        avg = avg / len(l)
        print(item," => ", d[item]," => ", avg)

dictionary = dataload()
printdictionary(dictionary)    

# output:
#bob  =>  [30.0]  =>  30.0
#zor  =>  [10.0, 21.0, 24.0]  =>  18.333333333333332
#qwerty  =>  [46.0]  =>  46.0

此代码背后的想法如下:在dataload方法中,python从textfile(字符串或其他地方)读取检查并将它们放入字典中,其中value是检查评估列表。在printdictionary方法中,计算平均分数并将结果显示给用户。