具有多个属性和混合顺序的列表排序 [英] List sorting with multiple attributes and mixed order
问题描述
我必须对具有多个属性的列表进行排序.我可以轻松地按升序对所有属性进行此操作
I have to sort a list with multiple attributes. I can do that in ascending order for ALL attributes easily with
L.sort(key=operator.attrgetter(attribute))....
但是问题是,我必须使用混合配置进行升序/降序...我必须模仿" SQL Order By
,在其中可以执行类似name ASC, year DESC
的操作.
有没有一种方法可以在Python中轻松实现,而无需实现自定义比较功能?
but the problem is, that I have to use mixed configurations for ascending/descending... I have to "imitate" a bit the SQL Order By
where you can do something like name ASC, year DESC
.
Is there a way to do this easily in Python without having to implement a custom compare function?
推荐答案
如果您的属性是数字属性,那么您就有了.
If your attributes are numeric, you have this.
def mixed_order( a ):
return ( a.attribute1, -a.attribute2 )
someList.sort( key=mixed_order )
如果您的属性包含字符串或其他更复杂的对象,则可以选择.
If your attributes includes strings or other more complex objects, you have some choices.
.sort()
方法很稳定:您可以进行多次遍历.这也许是最简单的.它也非常快.
The .sort()
method is stable: you can do multiple passes. This is perhaps the simplest. It's also remarkably fast.
def key1( a ): return a.attribute1
def key2( a ): return a.attribute2
someList.sort( key=key2, reverse=True )
someList.sort( key=key1 )
如果这是唯一的排序,则可以定义自己的专用比较运算符.最少需要__eq__
和__lt__
.其他四个可以通过简单的逻辑从这两个派生.
If this is the only sort, you can define your own special-purpose comparison operators. Minimally, you need __eq__
and __lt__
. The other four can be derived from these two by simple logic.
这篇关于具有多个属性和混合顺序的列表排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!