The example in this article describes how Python sorts the list. Share to everyone for your reference. The specific analysis is as follows:
1. Sort () function
The sort () function sorts the list using a fixed sorting algorithm. The sort () function changes the original list when the list is sorted, allowing the elements to be arranged in a certain order, rather than simply returning a sorted copy of the list.
Note that the sort () function changes the original list, and the function return value is null or none. Therefore, it is not straightforward to use the sort () function directly if you need an ordered list copy and keep the original list intact. To do this, use sort () to get the copy y of the list x first, and then sort the Y. The code is as follows:
X=[4,6,2,1,7,9,4]y=x[:]y.sort () Print xprint y
The results are as follows:
[4, 6, 2, 1, 7, 9, 4]
[1, 2, 4, 4, 6, 7, 9]
Description: Call x[:] Gets a shard that contains all the elements of X, which is a very efficient way to replicate the entire list. It is no use using y=x to simply copy X to Y, because doing so allows both X and Y to point to the same list.
2. Sorted () function
Another way to get a sorted copy of a list is to use the sorted () function. Note that the sorted () function can be used for any object that can be iterated.
x=[4,6,2,1,7,9,4]y=sorted (x) print xprint y
Results:
[4, 6, 2, 1, 7, 9, 4]
[1, 2, 4, 4, 6, 7, 9]
Hopefully this article will help you with Python programming.