The sort method in Python uses the detailed _python

Source: Internet
Author: User

The sort () method in Python is used for array sorting, which is described in detail in the form of an instance:

First, the basic form
the list has its own sort method, which sorts the list in situ, and since it is an in-place order, it is obvious that tuples cannot have this method because tuples are not modifiable.

x = [4, 6, 2, 1, 7, 9]
x.sort ()
print x # [1, 2, 4, 6, 7, 9]

If you need a sorted copy and keep the original list unchanged, how do you implement it?

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[:] Copy all the elements of list x to Y by slicing, and if you simply assign X to Y:y = x,y and x or point to the same list, no new copy is generated .

Another way to get a sorted list copy is to use the sorted function:

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]

Sorted returns an ordered copy, and the type is always listed as follows:

Print sorted (' Python ') #[' P ', ' h ', ' n ', ' o ', ' t ', ' Y ']

Two, the custom comparison function

You can define your own comparison functions and pass parameters to the Sort method:

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 # descending sort [8, 3, 2, 1, 0]
nums.sort (CMP) # Call BUILTIN function CMP, sorted in ascending order
print Nums # Descending sort [0, 1, 2, 3, 8]

Third, optional parameters

The Sort method also has two optional parameters: Key and reverse

1, key in use must provide a sort process of the total call function:

x = [' mmm ', ' mm ', ' mm ', ' m ']
x.sort (key = len)
print x # [' m ', ' mm ', ' mm ', ' mmm ']

2, reverse implementation descending sort, you need to provide a Boolean value:

y = [3, 2, 8, 0, 1]
y.sort (reverse = True)
print y #[8, 3, 2, 1, 0]

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.