This article mainly introduces the sort method in python. Friends who need it can refer to the following
The sort() method in Python is used for array sorting. This article explains it in detail in the form of examples:
1. Basic form
The list has its own sort method, which sorts the list in-place. Since it is in-place sorting, it is obvious that the tuple cannot have this method, because the tuple Groups cannot be modified.
x = [4, 6, 2, 1, 7, 9] x.sort() print x # [1, 2, 4, 6, 7, 9]
If you need a sorted copy while keeping the original list unchanged, how to achieve it
x =[4, 6, 2, 1, 7, 9] y = x[ : ] y.sort() print y #[1, 2, 4, 6, 7, 9] print x #[4, 6, 2, 1, 7, 9]
Note: y = x[:] The list will be All elements of x are copied to y. If x is simply assigned to y: y = x, y and x still point to the same list, and no new copies are generated .
Another way to get a copy of a sorted list is to use the sorted function:
x =[4, 6, 2, 1, 7, 9] y = sorted(x) print y #[1, 2, 4, 6, 7, 9] print x #[4, 6, 2, 1, 7, 9]
sorted returns an ordered copy, and the type is always a list, as follows :
print sorted('Python') #['P', 'h', 'n', 'o', 't', 'y']
2. Custom comparison function
You can define your own comparison function and then pass it to the sort method through parameters:
def comp(x, y): if x < y: return 1 elif x > y: return -1 else: return 0 nums = [3, 2, 8 ,0 , 1] nums.sort(comp) print nums # 降序排序[8, 3, 2, 1, 0] nums.sort(cmp) # 调用内建函数cmp ,升序排序 print nums # 降序排序[0, 1, 2, 3, 8]
3. Optional parameters
The sort method also has two optional parameters: key and reverse
1. The key is When using it, you must provide a function that is called by the sorting process:
x = ['mmm', 'mm', 'mm', 'm' ] x.sort(key = len) print x # ['m', 'mm', 'mm', 'mmm']
2. To reverse in descending order, you need to provide a Boolean value:
y = [3, 2, 8 ,0 , 1] y.sort(reverse = True) print y #[8, 3, 2, 1, 0]
[Related recommendations]
1 . Detailed explanation of how to use sort() in Python
2. Detailed explanation of the example tutorial of using values() in Python
3. Usage example of sort_values isin in pandas DataFrame
The above is the detailed content of Share examples of how to use sort in python. For more information, please follow other related articles on the PHP Chinese website!