在具有类的列表上使用python排序函数

2024-10-02 20:35:09 发布

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

我目前正在尝试使用内置的Sorted函数对一个名为scores的class属性的列表进行排序。你知道吗

在这里,排序函数只处理一个列表,它正确地按升序排列分数。你知道吗

Scores = [1,5,19,0,900,81,9000]


print(sorted(Scores))

但是,当我尝试将此函数应用于具有class属性的列表时,会返回一个错误: AttributeError:“list”对象没有“Score”属性

这是我的密码:

print(sorted(RecentScores.Score))

任何帮助都将不胜感激。你知道吗

下面是我正在初始化的班级和最近的分数表

class TRecentScore():
  def __init__(self):
    self.Name = ''
    self.Score = 0

RecentScores = [1,5,0]

Tags: 函数self列表属性排序内置分数class
3条回答

在类定义中,必须首先将__init__中的名称和分数作为输入,如下所示:

class TRecentScore():
    def __init__(self, Name, Score):
        self.Name = Name
        self.Score = Score

只有在类内指定名称和分数才有意义。 接下来,必须实例化类RecentScoresTRecentScore实例,将名称和分数作为参数传递给初始化。具体操作如下:

RecentScores = TRecentScore('Recent Scores',[1,5,0])
print(sorted(RecentScores.Score))

这将打印出排序后的分数。希望这有帮助!你知道吗

如果您总是希望对分数列表进行排序,可以对列表进行排序,使用“排序”创建新列表:

class TRecentScore():
    def __init__(self, name, score):
        self.Name = name
        self.score = score
        self.score.sort()

RecentScores = TRecentScore("score list", [1,5,19,0,900,81,9000])
print (RecentScores.score)
[0, 1, 5, 19, 81, 900, 9000]

你没有使用你的类,实际上你只是在声明一个包含一些数字的列表,然后你试图调用这个列表对象的属性Score。你知道吗

class TRecentScore():
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores

recent_scores = TRecentScore('Sorted Scores', [1,5,0])
print(sorted(recent_scores.scores))

相关问题 更多 >