For details, please refer to the official website of Liao Xuefeng, here are just a few excerpts, experience and practice of coding.
Python's built-in sorted()
functions can sort the list:
>>> sorted ([5, -12, 9, -21]) [-21,-12, 5, 9, 36]
sorted()
A function is also a higher-order function, and it can also receive a key
function to implement a custom sort, for example, by absolute size:
>>> sorted ([5, -12, 9, -21], key=ABS) [5, 9,-12,-21, 36]
- It is important to emphasize that sorted will only pass the elements of the first parameter list into the function specified by the key, not the entire list.
- To reverse order, you do not have to change the key function, you can pass in the third argument
reverse=True
:
>>> Sorted (['Bob',' About','Zoo',' Credit'], Key=str.lower, reverse=True) ['Zoo',' Credit','Bob',' About']
sorted()
the key to sorting is to implement a mapping function.
- Practice
- Suppose we use a group of tuples to represent student names and scores:
L = [(‘Bob‘, 75), (‘Adam‘, 92), (‘Bart‘, 66), (‘Lisa‘, 88)]
Please sorted()
sort the above list by name:
# -*-coding:utf-8-*- L = [('Bob', '), ('Adam', "), ('Bart') ('Lisa', ")]def by_name (t): return = sorted (L, key=by_name)print(L2)
- Then sort by grades from highest to lowest:
# -*-coding:utf-8-*- L = [('Bob', '), ('Adam', "), ('Bart') ('Lisa', ")]def By_score (t): return t[1= sorted (L, key=by_score)print(L2)
Python High-order function--Sorted