Python3----functions (sort and sorted)

Source: Internet
Author: User

In the process of learning Python, it feels like the sort in Python is similar to a generic algorithm in C + +, but it is easier to use relative to C + +.

The built-in function of the list in Python sort () sorts the elements in the list, while the global sorted () function applies to all iterations of the sequence, and the sort () function is a built-in function that changes the current object. The sorted () function returns only a copy of the sorted current object, without altering the current object.

1. Built-in function sort ()

Prototype: Sort (fun,key,reverse=false)

Parameter fun is to show that this sort function is based on what algorithm to sort, generally by default Python is a merge sort, and generally we will not override this parameter, so basically can be ignored;

The parameter key is used to specify a function, which is called every time the element is compared, and this function represents the ordered rule, that is, what rules you follow to sort your sequence;

The parameter reverse is used to indicate whether to reverse the order, and the default false is to sort by ascending rules, and when reverse=true, it is sorted in descending order.

The following is a simple example of the explanation:

1  fromoperatorImportAttrgetter,itemgetter2 3List1 = [(2,'Huan', 23), (12,' the', 14), (23,'Liu', 90)]4 5 #sort using default parameters, which are sorted by the first element in a tuple6 List1.sort ()7 Print(List1)8 #The output is [(2, ' Huan ', ") , ((+), ' the ', ' + '), (+, ' Liu ', ')]9 Ten #use an anonymous expression to override the function represented by key and sort by the second element of the tuple OneList1.sort (key=LambdaX: (x[1])) A Print(List1) - #[(2, ' Huan ', "), (%, ' Liu ', " a "), (+, ' the ', +)] -  the #use an anonymous expression to override the function represented by key and sort by the third element of a tuple -List1.sort (key=LambdaX: (x[2])) - Print(List1) - #[(2 , ' the ', "+), (Huan, ' + '), (at +, ' Liu ', ')] +  - #use the anonymous function to override the function represented by key, and first sort by a tuple labeled 2, + #for the same element at subscript 2, sort by the element labeled 0 AList1.sort (key=LambdaX: (x[2],x[0])) at Print (List1) - #[(2 , ' the ', "+), (Huan, ' + '), (at +, ' Liu ', ')] -  - #Use the Itemgetter function in the operator module to override the function represented by key, sorting by the element at index 1 -List1.sort (Key=itemgetter (1)) - Print (List1) in #[(2, ' Huan ', "), (%, ' Liu ', " a "), (+, ' the ', +)] -  to #Use the Itemgetter function in the operator module to override the function represented by key, sorting by the element at index 2 +List1.sort (Key=itemgetter (2)) - Print (List1) the #[(2 , ' the ', "+), (Huan, ' + '), (at +, ' Liu ', ')] *  $ #This can be analogous to the sorting method in lambda, no longer explainsPanax NotoginsengList1.sort (Key=itemgetter (2, 0)) - Print (List1) the #[(2 , ' the ', "+), (Huan, ' + '), (at +, ' Liu ', ')]

For the anonymous function mentioned above, if you do not understand it, you can get to know it, I will not expand here.

Here I would like to explain the operator two functions in this module:

(1) Itemgetter

operator.itemgetter(item) operator.itemgetter(*items) This function calls the __getitem__ () method of the incoming operand to return a callable object with item, and returns a callable object with a tuple type if the parameter passed in is multiple. For example: f = itemgetter(2)Callf(r), you will be returnedr[2]g = itemgetter(2, 5, 3)Callg(r)The tuple will be returned after the(r[2], r[5], r[3]). (2) Attrgetteroperator.attrgetter(attr) operator.attrgetter(*attrs) This function returns a callable object with the Attr property in the operand, and returns a tuple with these attributes if multiple properties are passed in. The names of these attributes can contain multiple sub-namesFor example:f = attrgetter(‘name‘)Callf(b)will returnb.name.f = attrgetter(‘name‘, ‘date‘)Callf(b)will return(b.name, b.date).f = attrgetter(‘name.first‘, ‘name.last‘)Callf(b)will return(b.name.first, b.name.last).

2. Global function sorted ()

The override of key in the sorted () function is the same as in the sort () function, so the method just described in sort () is applicable to the sorted () function, which I will not enumerate in the explanations below. And the following key rewrite is also applicable to the sort () function, then why no longer listed in the sort () function, that is to be impartial, to give you an objective understanding.

The following is still a sample cut:

1  fromoperatorImportAttrgetter2 classData:3Article_name =str ()4Readers =05     def __init__(SELF,TPL):6Self.article_name =Tpl[0]7Self.readers = tpl[1]8     defGetKey (self):9         returnself.readersTen     def __str__(self): One         returnSTR (str (self.article_name) +STR (':')+str (self.readers)) A  -List1 = [Data ("Java"), Data ("C + +"), Data ("python"), Data ("C + +", 90))] -  the #Call the Attrgetter function here to sort by readers -List2 = sorted (List1,key=attrgetter ("Readers")) - """result is - python:89 + c++:90 - java:100 + c++:100 A """ at  - #This allows the list1 to be sorted by Article_name first, sorted by readers for the same name -List3 = sorted (List1,key=attrgetter ("Article_name","Readers")) - """ - The result is: - c++:90 in c++:100 - java:100 to python:89 + """ -  the #using a custom function in a class can also be manipulated *List4 = sorted (List1,key =Data.getkey) $ """Panax Notoginseng The result is: - python:89 the c++:90 + java:100 A c++:100 the """

The results of the above example are printed out.

For the sorted () function, you can also use the method described in the sort () function, and you can try it yourself.

Of course, finally, in all the above examples I did not use the reverse parameter, for this parameter, is used to control the direction of the sorting, you can try it yourself, here is not introduced.

Python3----functions (sort and sorted)

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.