Detailed explanation of how to use sort() in Python
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

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? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Fastapi ...

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

Using python in Linux terminal...

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