On the sort and sorted functions in Python

Source: Internet
Author: User

sorted (...)

Help on built-in function sorted in module __builtin__:

Sorted (...)

Sorted (iterable, Cmp=none, Key=none, Reverse=false)--New sorted list

Sort (...)

Help on built-in function sort:
Sort (...)
L.sort (Cmp=none, Key=none, Reverse=false)-stable sort *in place*;
CMP (x, y)-1, 0, 1

The difference between sorted and sort

1. The sorted function is built-in, and sort is the intrinsic function of the sequence, so they are called differently, and the sorted function has a series of iterator references

2. The sorted function does not change the series of parameters. But it returns the ordered copy of the sequence, and sort acts as the inner function of the sequence, and the sequence of calls is sorted after the call is finished.

The following results are a good illustration of these:

>>> list=[2,1]>>> x=sorted (list) >>> x[1, 2]>>> list[2, 1]>>> y=list.sort () >>> y>>> list[1, 2]

Sorted and sort are sorted and sort except that one is a sequence as a parameter, and one is a sequence that calls the function. The other parameters are almost identical, each of which describes its use and effect:

1. Default method of Use

Because the reverse,key,cmp of the sort function provides a default number of parameters, we are able to call the function without specifying these parameters directly.

But it must have a premise. The type that is stored in the list is comparable. Otherwise, the error "type Error:unorderable type" will pop up.

2. Reverse number of references

When the value is true, it is the reverse row. False positive sequence from small to large row

>>> List.sort (reverse=false) >>> list[1, 2]>>> list.sort (reverse=true) >>> list[2 , 1]

3. Key Parameter key indicates the value to be used for comparison. This is primarily useful for the type of data that you define. Here is a sample to illustrate:
# Definition for a interval.class interval:def __init__ (self, s=0, e=0): Self.start = Sself.end = e# Initialize the Interv Al Listlist = []for i in Range (10,7,-1): to J in range (11,i,-1): List.append (Interval (I,J))
Here we define the data structure of interval [s,e] and initialize it. For this problem. Obviously we use the default parameters to invoke the error. Since we have not provided comparable functions to compare the types of interval.

In this case, we can specify the more key to solve.

#Sort the Interval listlist2 = sorted (List,key=lambda x:x.start) #Output the Interval listfor x in List:print ("[%d,%d]"% (x. Start,x.end))) for X in List2:print ("[%d,%d]"% (x.start,x.end))
Here we sort based on the Interval.start as key.
But then the question came. Suppose I not only compare interval.start, when Interval.start equal, still want to compare interval.end, what should do?
#Sort the Interval list based on interval.start and interval.endlist2 = sorted (List,key=lambda x: (x.start,x.end))
We use Ganso (interval.start,interval.end) as key to compare. The meta-ancestor has the default CMP function. This achieves the goal.
4. CMP parameters We are able to pass the reference to CMP using our own defined function or with a simple lambda
#Sort the Interval list based on Interval.start and Interval.enddef Cmpinterval (A, B): if A.start! = B.start:return CMP (A.S Tart,b.start) return CMP (a.end,b.end) List1 = sorted (list,cmp = cmpinterval) List2 = sorted (list,cmp = Lambda x,y:cmp ( X.start,y.start))
It's just a pity. There is an error in the introduction of the CMP function in Python 3.x today:TypeError: ' CMP ' is a invalid keyword argument for this functionAt this point we need to use key to circumvent this problem. Another suggestion is that we try to sort by using key instead of CMP to improve execution speed.



On the sort and sorted functions in Python

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.