Original article was published by Yong Cui, Ph.D. on Artificial Intelligence on Medium
9. Sorting With Different Order Requirements
Sorting items in a list is a prevalent task in many projects. The most basic sorting is based on the numeric or alphabetic order, and we can use the built-in
sorted() function. By default, the
sorted() function will sort the list (actually, it can be any iterable) in the ascending order. If we specify the
reverse argument to be
True, we can get the items in the descending order. Some simple usages are shown below.
Besides these basic usages, we can specify the
key argument such that complicated items can be sorted, such as a list of tuples. Consider the following example for such a case.
The above code shows you the two advanced sorting examples by leveraging a lambda function, which is passed to the
key argument. The first one is sorting the items using a descending order, while the second one is using the default ascending order. What if we want to combine these two requirements? If you think about playing with the
reverse argument, you probably bark up the wrong tree, because if you’re trying to sort by multiple criteria, the reverse argument will apply to all. What’s the trick then? See the code snippet below.
As you can see, by setting the
reverse argument to
False, neither worked. Instead, the trick is to negate the grades, and thus when you sort by the default ascending order, the scores will be sorted reversely because of the negation of these values. However, there is a caveat for this method, because negation can only work with numeric values, but not strings.