我有一个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降序排序列表?
当前回答
一种最快的方法是使用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)
# 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)
更多关于按键排序的信息。
一种最快的方法是使用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
向对象类添加丰富的比较运算符,然后使用列表的sort()方法。 参见python中的丰富比较。
更新:虽然这种方法可以工作,但我认为来自tritych的解决方案更适合你的情况,因为更简单。
此外,如果有人想对包含字符串和数字的列表进行排序。
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)