如何对测验完成3次时获得的分数进行排序?

时间:2016-02-29 19:52:07

标签: python sorting dictionary alphabetical-sort

当用户从最高分到最低分三次进行此测验时,我如何对用户获得的分数进行排序?另外,我如何按字母顺序对用户名进行排序,在运行代码时,他们的分数旁边是他们的分数?

school_data = []
for x in range (0,3):
    quiz = dict()
    print ("Enter your name")
    quiz['name'] = input()
    print ("what class")
    quiz['class_code'] = input()

    print("1. 9+10=")
    answer = input()
    answer = int(answer)

    if answer == 19:
        print("correct")
        score = score + 1
    else:
        print("wrong") 
    print("2. 16+40=")
    answer = input()
    answer = int(answer)
    if answer == 56:
        print("correct")
        score = score + 1
    else:
        print("wrong")

    print("3. 5+21=")
    answer = input()
    answer = int(answer) 
    if answer == 26:
        print("correct")
        score = score + 1
    else:
        print("wrong")

    print("4. 5-6=")
    answer = input()
    answer = int(answer)
    if answer == -1:
        print("correct")
        score = score + 1
    else:
        print("wrong")

    print("5. 21-9=")
    answer = input()
    answer = int(answer)

    if answer == 12:
        print("correct")
        score = score + 1
    else:
        print("wrong")
    quiz['score'] = score
    school_data.append(quiz)

1 个答案:

答案 0 :(得分:0)

您可以使用

按分数对school_data列表进行排序
sorted_school_data = sorted(school_data, key=lambda k: k['score'])

默认情况下,这首先排序得分最低,所以从最高到最低只做

sorted_school_data = sorted(school_data, key=lambda k: k['score'])[::-1]

要打印得分和姓名,您可以

for i in sorted(school_data, key=lambda k: k['name']):
    print('%s:%s' %(i['name'], i['score']))