Python instance analysis of the List sorting method
This article describes how to sort the list by Python. Share it with you for your reference. The specific analysis is as follows:
1. sort () function
The sort () function uses a fixed Sorting Algorithm to sort the list. The sort () function changes the original list when sorting the list, so that the elements in the list can be arranged in a certain order, rather than simply returning a copy of the sorted list.
Note that the sort () function changes the original list. The return value of the function is null, that is, None. Therefore, you cannot simply use the sort () function if you need an ordered copy of the list and keep the original list unchanged. To implement the above functions, the sort () method is to first obtain the copy Y of list X and then sort Y. The Code is as follows:
?
|
1
2
3
4
5 |
X = [, 4]
Y = x [:]
Y. sort ()
Print x
Print y
|
The result is as follows:
[4, 6, 2, 1, 7, 9, 4]
[1, 2, 4, 4, 6, 7, 9]
Note: Calling x [:] produces shards that contain all elements of x. This is a very efficient way to copy the entire list. It is useless to simply copy x to y through y = x, because this allows both x and y to point to the same list.
2. sorted () function
The sorted () function is used to obtain the sorted list copies. Note that the sorted () function can be used for any iteratable objects.
?
|
1
2
3
4 |
X = [, 4]
Y = sorted (x)
Print x
Print y
|
Result:
[4, 6, 2, 1, 7, 9, 4]
[1, 2, 4, 4, 6, 7, 9]
I hope this article will help you with Python programming.