我有一个Python对象列表,我想按每个对象的特定属性排序:
>>> ut
[Tag(name="toe", count=10), Tag(name="leg", count=2), ...]
我如何按.count降序排序列表?
我有一个Python对象列表,我想按每个对象的特定属性排序:
>>> ut
[Tag(name="toe", count=10), Tag(name="leg", count=2), ...]
我如何按.count降序排序列表?
当前回答
它看起来很像Django ORM模型实例的列表。
为什么不这样排序呢:
ut = Tag.objects.order_by('-count')
其他回答
# 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)
更多关于按键排序的信息。
向对象类添加丰富的比较运算符,然后使用列表的sort()方法。 参见python中的丰富比较。
更新:虽然这种方法可以工作,但我认为来自tritych的解决方案更适合你的情况,因为更简单。
它看起来很像Django ORM模型实例的列表。
为什么不这样排序呢:
ut = Tag.objects.order_by('-count')
一种最快的方法是使用operator.attrgetter("count"),尤其是当列表中有很多记录时。但是,这可能运行在Python的预操作符版本上,因此最好有一个备用机制。那么,你可能想做以下事情:
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
from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)