When sorting by SQL
Select * from table Order By key1 DESC, key2 ASC
You can specify the ascending / descending order of each key as in.
In C / C ++ etc., you can do the same by defining the comparison function yourself.
int compare(const MyStruct *a, const MyStruct *b)
{
if(a->k1 == b->k1){
return b->k2 - a->k2;
}else{
return a->k1 - b->k2;
}
}
On the other hand, in Python, sort can only specify the key function and the overall ascending / descending order, so what should we do if we sort tuples with multiple elements in this way?
It was written in the official doc. https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts
Sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.
This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade
def multisort(xs, specs):
for key, reverse in reversed(specs):
xs.sort(key=lambda x: x[key], reverse=reverse)
return xs
Since Python sorting is a stable sorting, you can sort repeatedly by specifying the ascending / descending order in order from the key with the lowest priority. I see!!
Recommended Posts