Reprinted from the product is slightly Library http://www.pinlue.com/article/2020/04/0515/4910108650628.html
python sort () function is used to sort the list of the original, if the parameter is specified using the comparison function specified comparison function.
sort () method syntax:
1
list.sort(cmp=None, key=None, reverse=False)
parameter
cmp - optional parameter, if this parameter is a method of using the parameter designated for sorting.
key - is mainly used for the comparison element, only one parameter, the specific parameter is a function of iteration may be taken from the object, specify one of the elements in the iteration to be sorted.
reverse - collation, reverse = True descending, reverse = False ascending (default).
return value
This method does not return a value, but the target list will be sorted.
Examples
The following examples illustrate the sort () function using the method:
Examples
1
2
3
4
5
6
7
#!/usr/bin/python
# -*- coding: UTF-8 -*-
aList = [123, 'Google', 'Runoob', 'Taobao', 'Facebook'];
aList.sort();
print "List : ", aList
Examples of the above output results are as follows:
1
List : [123, 'Facebook', 'Google', 'Runoob', 'Taobao']
The following examples of the output list in descending order:
Examples
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# List
vowels = [ 'e', 'a', 'u', 'o', 'i'
# Descending
vowels.sort(reverse=True)
# Output
print 'descending output:', vowels
Examples of the above output results are as follows:
1
Fujo Export: [ 'u', 'o', 'i', 'e', 'a']
The following example demonstrates the output to sort through the elements specified in the list of lists:
Examples
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Get a list of the second element
def takeSecond(elem):
return elem[1]
# List
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# Specify the second element ordering
random.sort(key=takeSecond)
# Output category
print 'Sort the list:', random
Examples of the above output results are as follows:
1
Sort the list: [(4, 1), (2, 2), (1, 3), (3, 4)]