Python sort and sorted function code parsing, pythonsorted
This article focuses on the sort and sorted functions in Python.
I. sort Functions
The sort function is an internal function of the sequence.
Function prototype:
L.sort(cmp=None, key=None, reverse=False)
Function functions:
It sorts L in situ, that is, it does not return an ordered sequence copy, but changes the current sequence into an ordered sequence.
Parameter description:
(1) cmp Parameters
Cmp accepts a function and uses an integer as an example. The form is:
def f(a,b): return a-b
If the elements to be sorted are of another type, if logic a is smaller than logic B, the function returns a negative number; logic a is equal to logic B, and function 0 is returned; logic a is greater than logic B, and function returns a positive number.
(2) key Parameters
The key also accepts a function. The difference is that this function only accepts one element, in the following form:
def f(a): return len(a)
The Return Value of the function accepted by the key, indicating the weight of the element. The sort will sort the values according to the weight.
(3) reverse Parameters
Accept False or True to indicate whether to reverse
Example of sort:
(1) sort by element length
L = [{1:5,3:4},{1:3,6:3},{1:1,2:4,5:6},{1:9}]def f(x): return len(x)sort(key=f)print L
Output:
[{1: 9}, {1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}]
(2) sort by the value of the element whose key is 1 in each dictionary element.
L = [{1:5,3:4},{1:3,6:3},{1:1,2:4,5:6},{1:9}]def f2(a,b): return a[1]-b[1]L.sort(cmp=f2)print L
Output:
[{1: 1, 2: 4, 5: 6}, {1: 3, 6: 3}, {1: 5, 3: 4}, {1: 9}]
Ii. sorted Functions
The sorted function is a built-in function that accepts a sequence and returns an ordered copy.
The only difference between sort and sort is that a copy is returned.
Summary
The above is all about Python sort sorted function code parsing in this article. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!