简体   繁体   中英

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.

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

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:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM