A simple tutorial on using the sorted () function in Python, pythonsorted
Sorting Algorithm
Sorting is also a commonly used algorithm in programs. Whether you use Bubble sorting or quick sorting, the core of sorting is to compare the size of two elements. If it is a number, we can directly compare it, but what if it is a string or two dict? It is meaningless to directly compare the mathematical size. Therefore, the comparison process must be abstracted by functions. Generally, for two elements x and y, if x is considered as <y,-1 is returned. If x = y, 0 is returned. If x> y, then 1 is returned, so that the sorting algorithm does not need to care about the specific comparison process, but directly sorts the results according to the comparison.
The built-in sorted () function of Python can sort the list:
>>> sorted([36, 5, 12, 9, 21])[5, 9, 12, 21, 36]
In addition, the sorted () function is also a high-order function, which can receive a comparison function to implement custom sorting. For example, to sort data in reverse order, we can customize a reversed_cmp function:
def reversed_cmp(x, y): if x > y: return -1 if x < y: return 1 return 0
You can import the custom comparison function reversed_cmp to implement inverted sorting:
>>> sorted([36, 5, 12, 9, 21], reversed_cmp)[36, 21, 12, 9, 5]
Let's look at another example of string sorting:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'])['Credit', 'Zoo', 'about', 'bob']
By default, strings are sorted by ASCII size. Because 'Z' <'A', the result is that uppercase letters Z are placed before lowercase letters.
Now we propose that case-insensitive sorting should be performed in alphabetical order. To implement this algorithm, you do not need to make major changes to the existing code. You only need to define a case-insensitive comparison algorithm:
def cmp_ignore_case(s1, s2): u1 = s1.upper() u2 = s2.upper() if u1 < u2: return -1 if u1 > u2: return 1 return 0
Ignore the case to compare two strings. In fact, convert both strings to uppercase (or both to lowercase) before comparison.
In this way, we pass the above comparison function to sorted to achieve case-insensitive sorting:
>>> sorted(['bob', 'about', 'Zoo', 'Credit'], cmp_ignore_case)['about', 'bob', 'Credit', 'Zoo']
From the above example, we can see that the abstract capabilities of higher-order functions are very powerful, and the core code can be kept very concise.