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

Detailed explanation of how to use sort() in Python

May 25, 2017 am 11:14 AM

1. Basic form

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


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


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


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


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


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


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


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


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


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


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles