我的代码目前看起来像这样:
import csv #this imports the CSV module, which enables us to read the file easier than using file.readlines()
score_dict = {} #this creates an empty dictionary
class_file = open('Class-A.txt','r') #this opens the file and reads the lines inside
scores = csv.reader(class_file) #this stores the class_file data as a readable object (that can be stripped even though it is a list) into the variable scores
for line in scores: #this loops through the different scores in each line
if line: #this ignores and empty rows of text in the file
scores_list = [] #this creates an empty array that will contain the list of scores for each student
for key, column in enumerate(line):
if key != 0: #this ignores the first column of text in the file as that will be used as the key
scores_list.append(int(column.strip())) #this appends the array to containing scores that have been stripped of whitespace and newlines. It also converts the scores into integers because in the text file, the scores are strings.
score_dict[line[0]] = scores_list #this inserts the list of scores into the dictionary
exit
for key in sorted(score_dict):
print ("%s: %s" % (key, score_dict[key]))
我必须根据姓名按字母顺序打印每个学生的最高分。
如何对每个key
中的值进行排序?
答案 0 :(得分:1)
为了对每个学生的分数进行排序,您可以使用与排序字典键相同的功能。
假设您还要更新分数列表,可能的实现是:
for key in sorted(score_dict):
# sorting the values.
score_dict[key] = sorted(score_dict[key], reverse=True)
# print of the highest score.
print ("%s: %s" % (key, score_dict[key][0]))
请注意,在填充字典时也可以进行排序。
根据OP在评论中的要求,这里是一段代码,允许打印按其最高分排序的学生列表(这是我在之前编辑的答案中的解释)。请注意,假设已经订购了每个学生的分数列表。
ordered_keys = sorted(score_dict.keys(), key=lambda k: score_dict[k][0], reverse=True)
for key in ordered_keys:
print("%s: %s" % (key, score_dict[key][0]))
如果没有订购并且您不想为每个学生订购分数列表,则使用max
功能就足够了,即使用
ordered_keys = sorted(score_dict.keys(), key=lambda k: max(score_dict[k]), reverse=True)
有关sorted
功能的详细信息,您可以查看https://wiki.python.org/moin/HowTo/Sorting#Key_Functions。
答案 1 :(得分:0)
您希望max没有排序到打印每个学生的最高分:
for key in sorted(score_dict):
print (key, max(score_dict[key]))
如果您确实要将值从最高到最低排序,则只需对值进行排序并使用reverse = True:
sorted(score_dict[key], reverse=True)
但是,您不需要为了获得最大值而对列表进行排序。