Home  >  Article  >  Backend Development  >  Detailed explanation of how to use sort() in Python

Detailed explanation of how to use sort() in Python

高洛峰
高洛峰Original
2017-05-25 11:14:313314browse

1. Basic form

sorted(iterable[, cmp[, key[, reverse]]])
iterable.sort(cmp[, key[, reverse]])


Parameter explanation:
(1) iterable specifies the list or iterable to be sorted, needless to say;
(2 ) cmp is a function, which specifies the function for comparison when sorting. You can specify a function or lambda function, such as:
Students is a list of class objects. Each member has three fields. You can define the cmp function yourself when using sorted for comparison. , for example, here you want to sort by comparing the third data member, the code can be written like this:

students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
sorted(students, key=lambda student : student[2])


(3) key is a function, specifying which item of the elements to be sorted is used for sorting, the function uses To illustrate with the above example, the code is as follows:

sorted(students, key=lambda student : student[2])


The function of the lambda function specified by key is to remove the third field of the element student (ie: student[2]), so when sorted, it will be sorted by The third field of all students elements is used for sorting.
2. Common usage:
1. In-place sorting
1) The list has its own sort method, which sorts the list in-place. Since it is in-place sorting , then obviously tuples cannot have this method, because tuples cannot be modified.

x = [4, 6, 2, 1, 7, 9]
x.sort()
print x # [1, 2, 4, 6, 7, 9]


2. Copy sorting
1)[:] sharding method

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[:] passes The sharding operation copies all elements of list x 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 produced.
2) sorted method
sorted returns an ordered copy, and the type is always a list, as follows:

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] 
print sorted('Python') #['P', 'h', 'n', 'o', 't', 'y']


3. Advanced usage
1.Customized cmp comparison function

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]


2.Customized key and reverse
1.reverse implements descending sorting and needs to provide a Boolean value , the default is False (ascending order).
2. When using key, you must provide a function that is called by the sorting process:

alist = [('2', '3', '10'), ('1', '2', '3'), ('5', '6', '7'), ('2', '5', '10'), ('2', '4', '10')]
# 多级排序,先按照第3个元素排序,然后按照第2个元素排序:
print sorted(alist, cmp = None, key = lambda x:(int(x[2]), int(x[1])), reverse = False)
-------------------------------------------------------------------------------------------
[('1', '2', '3'), ('5', '6', '7'), ('2', '3', '10'), ('2', '4', '10'), ('2', '5', '10')]


4. operator.itemgetter function
The itemgetter function provided by the operator module It is used to obtain the data of which dimensions of the object. The parameters are some serial numbers (that is, the serial numbers of the data to be obtained in the object). See the example below.

a = [1,2,3]
>>> b=operator.itemgetter(1)   //定义函数b,获取对象的第1个域的值
>>> b(a)
2
>>> b=operator.itemgetter(1,0) //定义函数b,获取对象的第1个域和第0个的值
>>> b(a)
(2, 1)


It should be noted that the operator.itemgetter function does not obtain the value, but defines a function through which the function can be applied to the object to obtain the value.
Usage of itemgetter in sort:

from operator import itemgetter
alist = [('2', '3', '10'), ('1', '2', '3'), ('5', '6', '7'), ('2', '5', '10'), ('2', '4', '10')]
# 多级排序,先按照第3个元素排序,然后按照第2个元素排序:
print sorted(alist, cmp = None, key = itemgetter(2, 1), reverse = False)
print sorted(alist, cmp = None, key = lambda x:itemgetter(2, 1)(x), reverse = False)
print sorted(alist, cmp = None, key = lambda x:map(int, itemgetter(2, 1)(x)), reverse = False)
--------------------------------------------------------------------------------------------------
[('2', '3', '10'), ('2', '4', '10'), ('2', '5', '10'), ('1', '2', '3'), ('5', '6', '7')]
[('2', '3', '10'), ('2', '4', '10'), ('2', '5', '10'), ('1', '2', '3'), ('5', '6', '7')]
[('1', '2', '3'), ('5', '6', '7'), ('2', '3', '10'), ('2', '4', '10'), ('2', '5', '10')]


The above is the basics of using the sort() method in Python introduced by the editor. I hope it will be useful to everyone. Thank you for your help. If you have any questions, please leave me a message and I will reply to you in time!

【Related recommendations】

1. Share examples of how to use sort in python

2. Detailed tutorial on using values() in Python

3. Example of using sort_values ​​isin in pandas DataFrame

The above is the detailed content of Detailed explanation of how to use sort() in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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