Home > Backend Development > Python Tutorial > Detailed explanation of the use of sort method in python

Detailed explanation of the use of sort method in python

不言
Release: 2018-04-09 17:24:41
Original
3448 people have browsed it

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]
Copy after login

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]
Copy after login

Note: y = x[:] copies all the elements of the list x to y through the sharding operation. If you simply assign x to y: y = x , y and x still point to the same list, and no new copy is 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]
Copy after login

sorted returns an ordered Copy, and the type is always a list, as follows:

print sorted('Python') #['P', 'h', 'n', 'o', 't', 'y']
Copy after login

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]
Copy after login

3. Optional parameters

The sort method also has two optional parameters: key and reverse

1. When using key, you must provide a function that is called by the sorting process:

x = [&#39;mmm&#39;, &#39;mm&#39;, &#39;mm&#39;, &#39;m&#39; ]
x.sort(key = len)
print x # [&#39;m&#39;, &#39;mm&#39;, &#39;mm&#39;, &#39;mmm&#39;]
Copy after login

2. To reverse sort 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]
Copy after login


The above is the detailed content of Detailed explanation of the use of sort method in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template