[英]Outputting Highest/Average Score From List Of 3 (Value) For Each Student (Key) In A Dictionary Sorted From Highest To Lowest?
[英]Sorting a list inside dictionary keys - Highest score from a list of 3
之前我曾问过类似的问题,所以我表示歉意,但我读回了任务,但误读了原始要求。
因此,根据我在这里收到的反馈,这是我使用的代码:
def task3():
classList = {}
classSearch = input("Which class would you like to interrogate? ")
try:
with open("answers " + classSearch + ".txt", 'rb') as handle:
classList = pickle.loads(handle.read())
except IOError as error:
print ("Sorry, this file does not exist")
sortOption = int(input("Would you like sort the students in alphabetical order? Enter 1\n Would you like to sort the students by highest score? Enter 2 \nWould you like to sort students by their average score?Enter 3\n"))
if sortOption == 1:
x = sorted(classList.items())
for key, value in x:
value.sort()
value.reverse()
print (x)
因此,我实际上需要做的是输出每个学生的最高分数,并按姓名的字母顺序排序。 在classList词典中是一个学生的名字,然后是一个包含他们在测验中获得的最后3个分数的列表。 显然,这对多个学生是重复的。 任何帮助将不胜感激。
假设输入完全未排序,类似这样的事情应该起作用:
for name,highscore in [(student,max(classList[student])) for student in sorted(classList.keys())]:
print name,highscore
预计到达时间 :
根据要求提供说明。
classList是一个dict
,每个成员由一个键(学生的姓名)和一个值(该学生的分数列表)组成。
我建议的代码遍历一个预排序的元组列表,其中包含该学生的姓名和该学生的最高分数,依次打印每个元组。
列表理解在这里完成所有工作。
classList.keys()
生成一个包含学生姓名的列表。 在这种情况下,内置的sorted
函数将返回相同的按字母顺序sorted
函数。
列表理解就像一个for循环,遍历键列表,并构建一个元组列表。
你可能还说
sortedNames = sorted(classList.keys())
for student in sortedNames:
high_score = max(classList[student])
print student, high_score
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.