python 具有多个属性和混合顺序的列表排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1516249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List sorting with multiple attributes and mixed order
提问by Bernhard Vallant
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))....
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?
但问题是,我必须使用混合配置进行升序/降序......我必须“模仿”一些 SQL Order By
,你可以在其中执行类似name ASC, year DESC
. 有没有办法在 Python 中轻松做到这一点,而无需实现自定义比较函数?
回答by S.Lott
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.
如果您的属性包括字符串或其他更复杂的对象,您有一些选择。
The .sort()
method is stable: you can do multiple passes. This is perhaps the simplest. It's also remarkably fast.
该.sort()
方法是稳定的:您可以进行多次传递。这也许是最简单的。它也非常快。
def key1( a ): return a.attribute1
def key2( a ): return a.attribute2
someList.sort( key=key2, reverse=True )
someList.sort( key=key1 )
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.
如果这是唯一的排序,您可以定义自己的专用比较运算符。至少,您需要__eq__
和__lt__
。其他四个可以通过简单的逻辑从这两个导出。
回答by RedGlyph
A custom function will render your code more readable. If you have many sorting operations and you don't want to create those functions though, you can use lambda's:
自定义函数将使您的代码更具可读性。如果您有很多排序操作并且不想创建这些函数,则可以使用 lambda 的:
L.sort(lambda x, y: cmp(x.name, y.name) or -cmp(x.year, y.year))
回答by Luká? Lalinsky
You can't, but writing the compare function is easy:
你不能,但编写比较函数很容易:
def my_cmp(a, b):
return cmp(a.foo, b.foo) or cmp(b.bar, a.bar)
L.sort(my_cmp)