[英]Outputting Highest/Average Score From List Of 3 (Value) For Each Student (Key) In A Dictionary Sorted From Highest To Lowest?
I'm creating three ways that the scores of students in a class (which are stored in a dictionary called scores
) can be viewed. 我正在创建三种查看班级学生分数的方法(存储在名为
scores
的词典中)。
The first method is to view the highest score of each student (which is taken from each student's list (their value), which consists of between 1 and 3 scores), sorted in alphabetical order by the student's name (their entry's key). 第一种方法是查看每个学生的最高分数(取自每个学生的列表(他们的值),该分数由1到3个分数组成),并按字母顺序按学生姓名(其条目的键)进行排序。 This is done using the following code:
使用以下代码完成此操作:
for name, highScore in [(student,max(scores[student])) for student in sorted(scores.keys())]:
print(name, highScore)
The output of this: 此输出:
David Sherwitz 9
Michael Bobby 1
Tyrone Malone 6
The second method is to view the highest score of each student, sorted from highest to lowest. 第二种方法是查看每个学生的最高分数,从最高到最低排序。 The code I created for this:
我为此创建的代码:
sortB = []
for name, highScore in [(student, max(scores[student])) for student in scores.keys()]:
sortB += name, highScore
print(sortB)
The output of this: 此输出:
['David Sherwitz', 9, 'Michael Bobby', 1, 'Tyrone Malone', 6]
I would like this output to look similar to the output of the first method, but it doesn't? 我希望此输出看起来与第一种方法的输出相似,但不是吗? It's not also not sorted from highest to lowest.
也不是没有从最高到最低排序。 How can I make it do that?
我该怎么做呢?
The third method is to view the average score of each student, sorted from highest to lowest. 第三种方法是查看每个学生的平均分数,从最高到最低排序。 I haven't created the code for this yet, but I think it would be possible to modify the code for the second method so that it gets the average score instead, but I don't know how?
我还没有为此创建代码,但我认为可以修改第二种方法的代码,以便获取平均分,但是我不知道怎么做?
Just need to run .sort
on the 2nd column, which can be defined by key=lambda x: x[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)
Similarly, to sort by average, just replace max
with the average function: 同样,要按平均值排序,只需将
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)
Here's sorting with first method and using similar coding style: 这是第一种方法的排序,并使用类似的编码样式:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.