Sorting algorithms
Sorting is also an algorithm that is often used in programs. Whether you use bubble sorting or fast sorting, the core of the sort is to compare the size of the two elements. If it is a number, we can compare it directly, but what if it is a string or two dict? There is no point in directly comparing the size of mathematics, so the process of comparison must be abstracted by functions.
Python's built-in sorted() functions can sort the list:
sorted([36, 5, -12, 9, -21])[-21, -12, 5, 9, 36]
In addition, the sorted() function is also a higher-order function, which can also receive a key function to implement a custom sort, for example, by absolute size:
>>> sorted([36, 5, -12, 9, -21], key=abs)[5, 9, -12, -21, 36]
The function specified by key acts on each element of the list and sorts according to the result returned by the key function. Compare the original list with key=abs the processed list:
list = [36, 5, -12, 9, -21]keys = [36, 5, 12, 9, 21]
The sorted() function then sorts by keys and returns the corresponding elements of the list according to the corresponding relationship:
keys排序结果 => [5, 9, 12, 21, 36] | | | | |最终结果 => [5, 9, -12, -21, 36]
Let's look at another example of string ordering:
sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘])[‘Credit‘, ‘Zoo‘, ‘about‘, ‘bob‘]
By default, the string is sorted by the size of ASCII, because, as a ‘Z‘ < ‘a‘ result, uppercase letters are Z a preceded by lowercase letters.
Now, we propose that the sort should be ignored in case of alphabetical order. To implement this algorithm, you do not have to change the existing code much, as long as we can use a key function to map the string to ignore the case of sorting. Ignoring the case to compare two strings is actually the first to capitalize the strings (or all lowercase) before comparing them.
In this way, we pass sorted the key function and we can sort by ignoring the case:
>>> sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=str.lower)[‘about‘, ‘bob‘, ‘Credit‘, ‘Zoo‘]
To reverse sort, you can pass in the third parameter without having to change the key function reverse=True :
>>> sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=str.lower, reverse=True)[‘Zoo‘, ‘Credit‘, ‘bob‘, ‘about‘]
As you can see from the above example, the abstraction of higher-order functions is very powerful, and the core code can be kept very concise.
Summary
sorted()is also a higher-order function. sorted()the key to sorting is to implement a mapping function.
The sorted of Python