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]