我正在创建三种方法,可以查看班级中学生的分数(存储在名为scores的字典中)。
第一种方法是查看每个学生的最高分数(从每个学生的列表(他们的值)中取出来,其中包括1到3分),按学生姓名(他们的条目键)按字母顺序排序。这是使用以下代码完成的:
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]我希望这个输出看起来类似于第一个方法的输出,但它不是吗?它也不是从最高到最低的排序。我怎么能让它这么做?
第三种方法是查看每个学生的平均分数,从最高到最低排序。我还没有为此创建代码,但我认为可以修改第二种方法的代码,这样它才能得到平均分数,但是我不知道怎么做呢?
发布于 2016-05-22 23:33:45
只需要在第二列上运行.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替换为average函数:
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)https://stackoverflow.com/questions/37375260
复制相似问题