Sort by multiple keys using different orderings [duplicate]
Solution 1:
There is no built-in way to handle this. For the general case, you must sort twice: first by the secondary sort, then by the primary sort. As @Mark Ransom mentioned in his comment, in many cases the variables are numeric, and so you can use the negative value to flip the ordering.
If you know the type of the variable you're trying to sort on and how to work with it, you could also write a key function that returns a decreasing value for increasing keys. See this thread for an example for strings. (Basically, you take the negative of the ASCII numerical value of the characters.)
In Python 2, you could also use a cmp
function instead of a key, but this will likely make the sort slower. Whether it will make it too slow depends on how big and unsorted the list is. In Python 3, the cmp
argument is gone, but as @Mark Ransom notes you could use cmp_to_key
.
Solution 2:
items.sort(key = lambda obj: (obj.firstname, [(-ord(c) for c in obj.lastname)]))