因为作者本人也是刚学python不久,在看python官方文档的时候看到了 Lambda 函数,其中使用sort函数的地方看的有些迷惑,所以就查找了一些关于sort和sorted函数的资料,在此整理到博客
L.sort (Cmp=none, Key=none, Reverse=false)
Sorted (iterable, Cmp=none, Key=none, Reverse=false)
In this way, the sorted function is only one iterable parameter more than the sort function, and the rest is nothing different, iterable is an iterator parameter.
One
Sorted is a built-in function, sort is an intrinsic function of the list, so it is called in a different way, and the sorted function does not change its iterator parameters, returning a sorted copy of the sequence, but sort as the inner function of the list, after the call, the list itself is already sorted in order
L1 = [3,2,5,1,4]L2 = [3,2,5,1,4]L1.sort()print(‘L1:‘,L1)print(‘sorted:‘,sorted(L2))print(‘L2:‘,L2)
This code runs as a result of
L1: [1, 2, 3, 4, 5]
Sorted: [1, 2, 3, 4, 5]
L2: [3, 2, 5, 1, 4]
Second, key parameters
Key is a function with a parameter to extract the comparison value for each element
1. If we do not use the key parameter, the key is none by default
L = [(1,‘S‘),(3,‘E‘),(2,‘A‘)]L.sort()print(‘sort:‘,L)L = [(1,‘S‘),(3,‘E‘),(2,‘A‘)]print(‘sorted:‘,sorted(L))
The result of the above code operation is:
Sort: [(1, ' S '), (2, ' A '), (3, ' E ')]
Sorted: [(1, ' S '), (2, ' A '), (3, ' E ')]
2. Now we use the key parameter to extract the last element as the comparison value
def last(L): return L[-1]L = [(1,‘S‘),(3,‘E‘),(2,‘A‘)]L.sort(key = last)print(‘sort:‘,L)L = [(1,‘S‘),(3,‘E‘),(2,‘A‘)]print(‘sorted:‘,sorted(L,key = last))
The above code runs the result:
Sort: [(2, ' A '), (3, ' E '), (1, ' S ')]
Sorted: [(2, ' A '), (3, ' E '), (1, ' S ')]
3. Use the lambda anonymous function as the key parameter
With the Lambda keyword, you can create short, anonymous functions.
L = [(1,‘S‘),(3,‘E‘),(2,‘A‘lambda L : L[-1])print(‘sort:‘,L)L = [(1,‘S‘),(3,‘E‘),(2,‘A‘)]print(‘sorted:‘lambda L : L[-1]))
Operation result is;
Sort: [(2, ' A '), (3, ' E '), (1, ' S ')]
Sorted: [(2, ' A '), (3, ' E '), (1, ' S ')]
Three, reverse parameters
The reverse parameter is the default value False when the sequence is positive, and when reverse = true is in reverse order
L = [1,3,2]L.sort()print(L)L.sort(reverse = True)print(L)
The result of the operation is:
[1, 2, 3]
[3, 2, 1]
关于cmp函数,因为在Python3.x中已经取消了这个参数。。在此就不多说了
Summary of sort and sorted functions in Python