How to use sort () in Python

Source: Internet
Author: User
I. Basic form sorted (iterable [, cmp [, key [, reverse]) iterable. sort (cmp [, key [, reverse]) parameter explanation: (1) iterable specifies the list or iterable to be sorted. (2) cmp is a function, specifies the function for comparison during sorting. you can specify a function or lambda function. for example, students is the list of class objects. no member has three fields and s is used. I. Basic form

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


Parameter description:
(1) iterable specifies the list or iterable to be sorted. Needless to say;
(2) cmp is a function that specifies the function for comparison during sorting. you can specify a function or lambda function, such:
Students is the list of class objects. no member has three fields. you can set the cmp function when using sorted for comparison. for example, sort by comparing the third data member, the code can be written as follows:

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


(3) The key is a function that specifies which of the elements to be sorted for sorting. the code is as follows:

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


The lambda function specified by key is the third field (I .e., student [2]) of the element student. Therefore, when sorted is sorted, it is sorted by the third field of all students elements.
II. common usage:
1. original address sorting
1) The list has its own sort method, which sorts the list by the original address. since the list is sorted by the original address, it is obviously impossible for the tuples to have this method, because the 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 [:] copies all the elements of 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 copies are generated.
2) sorted method
Sorted returns an ordered copy, and the type is always listed 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']


III. Advanced usage
1. Custom cmp comparison functions

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 # sort [8, 3, 2, 1, 0] nums in descending order. sort (cmp) # Call the built-in function cmp to sort in ascending order print nums # sort in descending order [0, 1, 2, 3, 8]


2. Custom key and reverse
1. to sort data in descending order, you must provide a Boolean value. The default value is False (ascending order ).
2. when using the key, you must provide a function called in the sorting process:

Alist = [('2', '3', '10'), ('1', '2', '3'), ('5', '6 ', '7'), ('2', '5', '10'), ('2', '4', '10')] # Multi-level sorting, sort by 3rd elements first, and then sort by 2nd elements: print sorted (alist, cmp = None, key = lambda x :( int (x [2]), int (x [1]), reverse = False) values [('1', '2', '3'), ('5', '6 ', '7'), ('2', '3', '10'), ('2', '4', '10'), ('2 ', '5', '10')]


IV. operator. itemgetter function
The itemgetter function provided by the operator module is used to obtain the Dimension Data of an object. the parameter is a sequence number (that is, the sequence number of the data to be obtained in the object). The following is an example.

A = [1, 2, 3] >>> B = operator. itemgetter (1) // defines function B to obtain the value of the object's 1st fields >>> B (a) 2 >>> B = operator. itemgetter (1st) // defines function B and obtains the value of the object's 0th fields and >>> B (a) (2, 1)


Note that the operator. itemgetter function does not obtain a value, but defines a function that can be used to obtain a value only when it is applied to an object.
Usage of itemgetter in sort:

From operator import itemgetteralist = [('2', '3', '10'), ('1', '2', '3'), ('5 ', '6', '7'), ('2', '5', '10'), ('2', '4', '10')] # Multi-level sorting: first sort by 3rd elements, and then sort by 2nd elements: 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) counter [('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 basic usage of the sort () method in Python introduced by the small Editor. I hope it will be helpful to you. if you have any questions, please leave a message. The small editor will reply to you in time!

The above is a detailed description of the usage of sort () in Python. For more information, see other related articles in the first PHP community!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.