我创建了三种方法,可以查看班级中的学生分数(存储在名为scores
的词典中)。
第一种方法是查看每个学生的最高分(取自每个学生的名单(他们的价值),由1到3个分数组成),由学生按字母顺序排序&# 39;的名字(他们的条目的关键)。这是使用以下代码完成的:
for name, highScore in [(student,max(scores[student])) for student in sorted(scores.keys())]:
print(name, highScore)
输出:
David Sherwitz 9
Michael Bobby 1
Tyrone Malone 6
第二种方法是查看每个学生的最高分,从最高到最低排序。我为此创建的代码:
sortB = []
for name, highScore in [(student, max(scores[student])) for student in scores.keys()]:
sortB += name, highScore
print(sortB)
输出:
['David Sherwitz', 9, 'Michael Bobby', 1, 'Tyrone Malone', 6]
我希望这个输出看起来类似于第一种方法的输出,但它不是吗?它也没有从最高到最低排序。我该怎么做呢?
第三种方法是查看每个学生的平均分数,从最高到最低排序。我还没有为此创建代码,但我认为可以修改第二种方法的代码,以便获得平均分数,但我不知道怎么做?
答案 0 :(得分:1)
只需在第二列上运行.sort
,可由key=lambda x: x[1]
定义:
sortB = [(n, max(s)) for n,s in scores.items()]
sortB.sort(key=lambda x: x[1], reverse=True)
for name, highScore in sortB:
print(name, highScore)
同样,要按平均值排序,只需将max
替换为平均函数:
sortC = [(n, float(sum(s))/len(s)) for n,s in scores.items()]
sortC.sort(key=lambda x: x[1], reverse=True)
for name, avgScore in sortC:
print(name, avgScore)
这是使用第一种方法排序并使用类似的编码风格:
sortA = [(n,max(s)) for n,s in scores.items()]
sortA.sort(key=lambda x: x[0])
for name, highScore in sortA:
print(name, highScore)