对类实例 Python 的列表排序

我有一个类实例列表-

x = [<iteminstance1>,...]

在其他属性中,该类具有 score属性。如何根据这个参数按升序排序项目?

编辑 : python 中的 list有一个称为 sort的东西。我能用这个吗?如何指导这个函数使用我的 score属性?

140051 次浏览
import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

In addition to the solution you accepted, you could also implement the special __lt__() ("less than") method on the class. The sort() method (and the sorted() function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

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