Use of the built-in function sorted ()/list. sort ()
Simple application
Python has a built-in function: sorted () for sorting. Example:
>>> A = [5, 3, 6, 1, 9, 2]
>>> Sorted (a) # After a is sorted, a sorting result is obtained.
[1, 2, 3, 5, 6, 9] # However, the original a is not affected.
>>>
[5, 3, 6, 1, 9, 2]
You can also use list. sort () to perform the preceding operations.
>>> A. sort ()
>>> A # note that after list. sort (), the original
The sequence of [1, 2, 3, 5, 6, 9] # a has changed.
Differences between sorted and list. sort:
List. sort () can only sort the list type. As follows:
>>> B _dict = {1: 'e', 3: 'M', 9: 'A', 5: 'e '}
>>> B _dict.sort ()
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
AttributeError: 'dict 'object has no attribute 'sort'
Sorted is not. Let's look at the example:
>>> B _dict
{1: 'e', 3: 'M', 5: 'e', 9: 'A '}
>>> Sorted (B _dict)
[1, 3, 5, 9]
After sorted, in dictinoary, the key values are extracted and sorted, and the sorting results of the list type are returned.
Sort by specified keywords
In list. sort () and sorted, you can sort by specified key values. For example:
Sorted example:
>>> Qw = "I am Qiwsir you can read my articles im my blog". split ()
>>> Qw
['I', 'AM ', 'qiwsir', 'you', 'can ', 'read', 'My', 'Articles ', 'Im ', 'My, 'blog ']
>>> Sorted (qw, key = str. lower) # Sort by letter in ascending order
['AM ', 'Articles', 'blog ', 'can', 'I', 'Im ', 'My', 'My ', 'qiwsir ', 'read', 'you']
Example of list. sort:
>>> Qw
['I', 'AM ', 'qiwsir', 'you', 'can ', 'read', 'My', 'Articles ', 'Im ', 'My, 'blog ']
>>> Qw. sort (key = str. lower)
>>> Qw
['AM ', 'Articles', 'blog ', 'can', 'I', 'Im ', 'My', 'My ', 'qiwsir ', 'read', 'you']
In addition, the key can receive a single return value of the function, sorted by this value. For example:
>>> Name_mark_age = [('hangsan', 'A', 15), ('lisi', 'B', 14), ('hangzhou', 'A ', 16)]
>>> Sorted (name_mark_age, key = lambda x: x [2]) # Sort by age
[('Lisi', 'B', 14), ('hangsan', 'A', 15), ('hangzhou', 'A', 16)]
>>> Sorted (name_mark_age, key = lambda x: x [1]) # Sort by level
[('Hangsan', 'A', 15), ('hangww', 'A', 16), ('lisi', 'B', 14)]
>>> Sorted (name_mark_age, key = lambda x: x [0]) # Sort by name
[('Lisi', 'B', 14), ('hangzhou', 'A', 16), ('hangsan', 'A', 15)]
In addition to the preceding method, python also provides a module for selecting the specified values cyclically. Official documents: https://docs.python.org/2/library/operator.html#module-operator
>>> From operator import itemgetter
>>> Name_mark_age
[('Hangsan', 'A', 15), ('lisi', 'B', 14), ('hangww', 'A', 16 ), ('zhaoliu', 'B', 16)]
>>> Sorted (name_mark_age, key = itemgetter (2) # Sort by age
[('Lisi', 'B', 14), ('hangsan', 'A', 15), ('hangzhou', 'A', 16 ), ('zhaoliu', 'B', 16)]
>>> Sorted (name_mark_age, key = itemgetter (1, 2) # Sort by level first. Age is determined by level.
[('Hangsan', 'A', 15), ('hangww', 'A', 16), ('lisi', 'B', 14 ), ('zhaoliu', 'B', 16)]
In the official document, there is an example that is exactly the same as the above operations.
>>> Class Student:
Def _ init _ (self, name, grade, age ):
Self. name = name
Self. grade = grade
Self. age = age
Def _ repr _ (self ):
Return repr (self. name, self. grade, self. age ))
>>> Student_objects = [
Student ('John', 'A', 15), # note that class Student is used to generate values in the list.
Student ('Jane ',' B ', 12), # therefore, you can use student_objects [I]. age to access the age of a name. If I = 0, it is john's age.
Student ('Dave ',' B ', 10 ),
]
>>> Sorted (student_objects, key = lambda student: student. age)
[('Dave ',' B ', 10), ('Jane', 'B', 12), ('John', 'A', 15)]
The operator module can also be referenced to achieve the above sorting.
>>> From operator import attrgetter
>>> Sorted (student_objects, key = attrgetter ('age '))
[('Dave ',' B ', 10), ('Jane', 'B', 12), ('John', 'A', 15)]
>>> Sorted (student_objects, key = attrgetter ('grad', 'age '))
[('John', 'A', 15), ('Dave ',' B ', 10), ('Jane', 'B', 12)]
** Conclusion: ** sorted is powerful in sorting not only, but also by specified keywords.
The preceding example is in ascending order. If reverse = True is added. For example:
>>> From operator import itemgetter
>>> Name_mark_age
[('Hangsan', 'A', 15), ('lisi', 'B', 14), ('hangww', 'A', 16 ), ('zhaoliu', 'B', 16)]
>>> Sorted (name_mark_age, key = itemgetter (2), reverse = True)
[('Wangwu', 'A', 16), ('zhaoliu', 'B', 16), ('hangsan', 'A', 15 ), ('lisi', 'B', 14)]
Sorted algorithm
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', 'credentials']) ['credentials', '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', 'credentials'], cmp_ignore_case)
['About', 'Bob', 'credentials', '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.