I have to sort a python 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 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?
You can't, but writing the compare function is easy:
If your attributes are numeric, you have this.
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.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.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: