-1
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) 

我能够显示 aplhabetically 但无法显示从高到低文件类 4 包含变量名称和分数

约 9

z 4

b 6

a10

4

1 回答 1

0

该文件包含空行,您正在尝试将其拆分为列表并访问第二个元素。这就是您收到 IndexError 的原因。所以忽略空行。

而且你应该做 line.split() 因为没有逗号

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) 
于 2015-10-29T13:49:26.400 回答