将一个 .txt 文件中的数据从最高到最低排序并将其打印到另一个文本文件

Sorting data in one .txt file from highest to lowest and printing it to another text file

我为一位老师创建了一个测验,每个 class 的所有分数都存储在一个文件中,例如,如果一个学生在 class 1,他们的分数将被复制到一个名为 class1 的文本文件,数据的写法如下:

aaron, 1 
lllll, 10 
kkkkk, 7

但是我的下一个任务是创建另一个程序供老师使用,这样她就可以输入 class 她想要的内容以及她想要的内容(按字母顺序,平均数和从高到低)并打印出来它在 运行 时。到目前为止,这是我的代码,我已经设法完成了按字母顺序排列的部分,但在平均和从最高到最低的部分上苦苦挣扎:

viewclass= input("choose a class number and either alphabetically, average or highest?")


if viewclass=='1 alphabetically':
    with open('class1.txt', 'r') as r:
        for line in sorted(r):
             print(line, end='')


elif viewclass=='2 alphabetically':
    with open('class2.txt', 'r') as r:
        for line in sorted(r):
             print(line, end='')

elif viewclass=='3 alphabetically':
    with open('class3.txt', 'r') as r:
        for line in sorted(r):
             print(line, end='')

关键是定义正确的排序 key 并使用 reverse。我假设 'highest' 你想要以下内容。

r = '''\
aaron, 1
lllll, 10
kkkkk, 7'''.split('\n')
# r is an iterable of non-blank lines, like a file

def score(line):
    return int(line.split(',')[1])

for line in sorted(r, key=score, reverse=True):
    print(line)

###
lllll, 10
kkkkk, 7
aaron, 1

我不知道你所说的'average'是什么意思。