如何根据对象的属性对对象列表进行排序?

2022-09-05 01:06:16

我有一个Python对象列表,我想按每个对象的特定属性进行排序:

>>> ut
[Tag(name="toe", count=10), Tag(name="leg", count=2), ...]

如何按降序对列表进行排序?.count


答案 1
# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)

# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)

详细了解按键排序


答案 2

一种最快的方法,特别是如果您的列表有很多记录,是使用 。但是,这可能在Python的预运算符版本上运行,因此最好有一个回退机制。然后,您可能需要执行以下操作:operator.attrgetter("count")

try: import operator
except ImportError: keyfun= lambda x: x.count # use a lambda if no operator module
else: keyfun= operator.attrgetter("count") # use operator since it's faster than lambda

ut.sort(key=keyfun, reverse=True) # sort in-place

推荐