Python 类型错误:';排行榜';对象不支持索引

Python 类型错误:';排行榜';对象不支持索引,python,list,Python,List,我想打印出按第二个元素排序的列表 TypeError: 'top_list' object does not support indexing 有人能帮我吗 class top_list(object): def __init__(self, name, hit_rate): self.name = name self.hit_rate = float(hit_rate) def __str__(self): return "

我想打印出按第二个元素排序的列表

TypeError: 'top_list' object does not support indexing
有人能帮我吗

class top_list(object):

    def __init__(self, name, hit_rate):
        self.name = name
        self.hit_rate = float(hit_rate)

    def __str__(self):
        return "{0} {1}".format(self.name, self.hit_rate)


def top_ten():

    """Prints out the list"""
    top10 = []
    file = open("high_score.txt")
    for i in range(0,1):
        x = file.readlines()
    for line in x:
        line = line.split(",")
        lista = top_list(line[0], float(line[1]))
        top10.append(lista)

    a = sorted(top10, key=lambda line: line[1])
    print(a)
在代码中

a = sorted(top10, key=lambda line: line[1])
您正试图使用下标符号访问top_list元素。如果这就是您想要做的,那么实现一个
\uu getitem\uu
方法
\uuuu getitem\uuuu
允许您使用下标运算符-
list[1]
转换为
list.\uuuu getitem\uuuuu(1)

或者修改lambda函数以访问所需的元素,而不使用下标:

a = sorted(top10, key=lambda line: line.hit_rate)
还要注意的是,对文件使用上下文管理器更安全、更具python风格。您还可以通过迭代Python文件对象来读取这些行:

with open('high_score.txt', 'r') as file:
    for line in file:
        ...
但在处理换行代码时需要格外小心(可能会剥离它们)

with open('high_score.txt', 'r') as file:
    for line in file:
        ...