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

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

我如何按.count降序排序列表?


当前回答

此外,如果有人想对包含字符串和数字的列表进行排序。

 eglist=[
     "some0thing3",
     "some0thing2",
     "some1thing2",
     "some1thing0",
     "some3thing10",
     "some3thing2",
     "some1thing1",
     "some0thing1"]

下面是它的代码:

import re

def atoi(text):
    return int(text) if text.isdigit() else text

def natural_keys(text):
    return [ atoi(c) for c in re.split(r'(\d+)', text) ]

eglist=[
         "some0thing3",
         "some0thing2",
         "some1thing2",
         "some1thing0",
         "some3thing10",
         "some3thing2",
         "some1thing1",
         "some0thing1"
]

eglist.sort(key=natural_keys)
print(eglist)

其他回答

一种最快的方法是使用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

如果要排序的属性是属性,则可以避免导入操作符。Attrgetter并使用属性的fget方法。

例如,对于一个具有属性半径的类Circle,我们可以按照半径对圆圈列表进行排序,如下所示:

result = sorted(circles, key=Circle.radius.fget)

这并不是最著名的特性,但它常常为我节省一行导入。

它看起来很像Django ORM模型实例的列表。

为什么不这样排序呢:

ut = Tag.objects.order_by('-count')
from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)

此外,如果有人想对包含字符串和数字的列表进行排序。

 eglist=[
     "some0thing3",
     "some0thing2",
     "some1thing2",
     "some1thing0",
     "some3thing10",
     "some3thing2",
     "some1thing1",
     "some0thing1"]

下面是它的代码:

import re

def atoi(text):
    return int(text) if text.isdigit() else text

def natural_keys(text):
    return [ atoi(c) for c in re.split(r'(\d+)', text) ]

eglist=[
         "some0thing3",
         "some0thing2",
         "some1thing2",
         "some1thing0",
         "some3thing10",
         "some3thing2",
         "some1thing1",
         "some0thing1"
]

eglist.sort(key=natural_keys)
print(eglist)