如何从最高到最低显示文件的内容

2024-03-29 05:48:36 发布

您现在位置:Python中文网/ 问答频道 /正文

option= input("alphabetically(a), high to low(b)")
if option == "a":
    with open('Class4.txt', 'r') as r:
        for line in sorted(r):
            print(line)

elif option == "b":
            def score(line):
                return int(line.split(',')[1])

            with open('Class4.txt', 'r') as r:
                for line in sorted(r, key=score, reverse=True):
                    print(line) 

我能很好地表现出来,但不能从高到低 文件类4包含变量名和分数

ab第9页

z 4级

乙6

a10型


Tags: intxtforinputaswithlineopen
1条回答
网友
1楼 · 发布于 2024-03-29 05:48:36

文件包含空行,您正试图将其拆分为一个列表并访问第二个元素。这就是为什么你得到索引器。 所以忽略空行。你知道吗

你也应该这样做行。拆分()因为没有逗号

option= input("alphabetically(a), high to low(b)")
if option == "a":
    with open('Class4.txt', 'r') as r:
        for line in sorted(r):
            print(line)

elif option == "b":
        def score(line):
            if line != '\n':
                return int(line.split()[1])

        with open('Class4.txt', 'r') as r:
            for line in sorted(r, key=score, reverse=True):
                print(line) 

相关问题 更多 >