# This is a learning note for the Liaoche teacher Python tutorial
1 , overview
The python built-in sorted () function can sort the list.
The sorted () function is also a high-order function that can receive a key function to implement a custom sort, and the function specified by key will be applied to each element of the list and sorted according to the result returned by the key function.
# Direct Sort
>>> Sorted ([36, 5,-12, 9,-21])
[-21,-12, 5, 9, 36]
# Accept the key function sort
>>> sorted ([5, -12, 9, -21], key=abs)
[5, 9,-12,-21, 36]
# Sort by alphabetical order
>>> sorted ([' Bob ', ' about ', ' Zoo ', ' credits '], Key=str.lower) # sorted by default is ASCII sorted, and z>a, so need to add key function
[' About ', ' Bob ', ' credits ', ' Zoo ']
2 , examples
1,Suppose we use a group of tuples to represent student names and scores:L = [(' Bob ', the), (' Adam ', the), (' Bart ', the), (' Lisa ', the)]
Please use Sorted () The above list is sorted by name, respectively:
#-*-Coding:utf-8-*-
L = [(' Bob ', ', '), (' Adam ', ' the '), (' Bart ', ' the '), (' Lisa ', 88)]
# Sort by name
def by_name (t):
return t[0]
# Sort by score. -t[1], the higher thescore, the smaller the minus sign, the more forward
def by_score (t):
RETURN-T[1]
# Test
L2 = sorted (L, Key=by_name)
Print (L2)
# Sort by name
[(' Adam ', the "," (' Bart '), (' Bob ', '), (' Lisa ', 88)]
# Sort by score
[(' Adam ', "the"), (' Lisa ', ","), (' Bob ', '), (' Bart ', 66)]
Python Learning note __4.1.3 sorted