我需要知道如何对我的python字典按aveage分数对有多个分数的学生进行排序?

2024-05-14 10:46:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有班上许多参加测验的学生的名字。ome用了不止一个,我想用python计算出平均值。我把分数保存在一个文本文件中,但我不知道如何编程,所以它按总分除以他们参加考试的次数来排序。我正在使用python3.4.1。在

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

我试着按这个分类:

^{pr2}$

Tags: thetext排序编程名字次数学生分数
2条回答

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

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

然后创建一个新字典,在其中存储姓名和平均分数:

^{pr2}$

您的代码应该如下所示:

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]))

这对你有帮助吗?在

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是考试评估的列表。在printdiction方法中,计算平均分并将结果显示给用户。在

相关问题 更多 >

    热门问题