python - 对类实例列表进行排序 Python

标签 python sorting

我有一个类实例列表 -

x = [<iteminstance1>,...]

在其他属性中,该类具有 score 属性。如何根据此参数对项目进行升序排序?

EDIT:python中的list有一个叫做sort的东西。我可以在这里使用它吗?如何指示此函数使用我的 score 属性?

最佳答案

除了您接受的解决方案之外,您还可以在类上实现特殊的 __lt__()(“小于”)方法。 sort() 方法(和 sorted() 函数)将能够比较对象,从而对它们进行排序。但是,当您只根据该属性对它们进行排序时,这种方法效果最好。

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()

关于python - 对类实例列表进行排序 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4010322/

相关文章:

python - 如何获取当前的python解释器路径

python - Pygame - 如果你用一个比表面小的矩形来 blit 一个表面会发生什么?

python - Macos python 3.9 idle IDLE 无法导入 Tkinter

ios - tableview中的列数据排序

Matlab求向量中重复元素的间隔

python - 有没有更好的方法来合并两个集合的字典?

python - 获取 "TypeError: ' 模块的对象不可调用"与 `socket.socket()`

python - 在 python 中排序列表

javascript - 按内容对 div asc desc 进行排序

Java合并排序错误?继续获取输入值?