The python built-in sorted () function can sort the list:
>>>sorted ([36, 5, 12, 9, 21])
[5, 9, 12, 21, 36]
But sorted () is also a high-order function, which can receive a comparison function to implement a custom sort, the definition of the comparison function is to pass in two elements to be compared x, Y, if x should be in front of y, return-1, if X should be ranked after Y, return 1. returns 0 if x and y are equal.
So, if we're going to sort in reverse order, we just need to write a reversed_cmp function:
def reversed_cmp (x, y): if x > y: return-1 if x < y: return 1 return 0
In this way, call sorted () and pass in the reversed_cmp to achieve a reverse order:
>>> Sorted ([36, 21, 12, 9, 5], reversed_cmp) [[5, 9]
Sorted () can also sort strings, and strings are compared by default in ASCII size:
>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits ']) [' Credits ', ' Zoo ', ' about ', ' Bob ']
The ' Zoo ' was ranked before ' about ' because the ' Z ' ASCII code was smaller than ' a '.
Advanced function sorted () in Python