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.
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.