到目前为止,在我的代码中,我已经完成了它,以便显示平均值,并且可以按字母顺序对学生进行排序。但是,我需要更改我的代码,以便结果可以从最高到最低存储,但我正在努力解决这个问题。
在我的文本文件中,它看起来像这样:
名,3,4,5
2name,5,6,7
3name,3,4,5
每个名称不同
到目前为止,这是我的代码:
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def avg_mark(self):
return sum(self.marks)/len(self.marks)
def __str__(self):
return '{0}: {1}, {2}'.format(self.name, self.marks, self.avg_mark())
def load_grades(filename):
fd = open(filename, 'r')
f = {}
for line in fd:
split = line.split(',')
key = split[0]
marks = [int(n) for n in split[1:]]
try:
f[key] += marks
except KeyError:
f[key] = marks
students = []
for key, values in f.items():
students.append(Student(key, values[-3:]))
return students
def sort_by_name(students):
def get_name(student):
return student.name
students = sorted(students, key=get_name)
return students
def sort_by_avg(students):
def get_avg(student):
return student.avg_mark()
students = sorted(students, key=get_avg)
return students
again = True
while again:
class_num = input ('Which class do you want to view 1,2 or 3?')
print('please input a, b or c')
print('a)Alphabeically')
print('b)average')
print('c)highest to lowest')
sort = input ('how would you like to view it:')
if class_num =="1" and sort =="a":
students = load_grades('class1.txt')
students = sort_by_name(students)
elif class_num =="1" and sort =="b":
students = load_grades('class1.txt')
students = sort_by_avg(students)
for student in students:
print(student)
Again=input('Do you want to view another class yes or no?')
again = (Again=='yes')
print('bye')
我想要它,这样当按下c时,数字从最高到最低排序。
由于