Skip to main content
 首页 » 编程设计

python之在具有类的列表上使用 python Sorted 函数

2025年05月04日14powertoolsteam

我目前正在尝试使用内置函数 Sorted 对具有名为 scores 的类属性的列表进行排序。

这里的 sorted 函数只处理一个列表,它正确地按升序对分数进行排序。

Scores = [1,5,19,0,900,81,9000] 
 
 
print(sorted(Scores)) 

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

这是我的代码:

print(sorted(RecentScores.Score)) 

如有任何帮助,我们将不胜感激。

下面是我的类(class)正在初始化和 RecentScores 列表

class TRecentScore(): 
  def __init__(self): 
    self.Name = '' 
    self.Score = 0 
 
RecentScores = [1,5,0] 

请您参考如下方法:

你并没有使用你的类,你实际上在做的只是声明一个包含一些数字的列表,然后你试图调用属性 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))