The sort method in python USES elaboration

  • 2020-04-02 13:52:30
  • OfStack

The sort() method in Python is used to sort arrays, which this article details as an example:

I. basic form
Lists have their own sort method, which sorts the list by its original address, and since it's the original address sort, it's obviously impossible for tuples to have this method, because tuples are unmodifiable.


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

How do you do this if you want a sorted copy of the list, while keeping the original list the same


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[:] copies all the elements of list x to y by sharding. If you simply assign x to y: y = x, y and x still point to the same list, and no new copy is produced.

Another way to get a copy of the sorted list 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 a list, as follows:


print sorted('Python') #['P', 'h', 'n', 'o', 't', 'y']

Two, custom comparison function

You can define your own comparison function and pass it to the sort method as an argument:


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 order [8, 3, 2, 1, 0]
nums.sort(cmp) #  Call the built-in function cmp  Sort in ascending order 
print nums #  Descending order [0, 1, 2, 3, 8]

Optional parameters

The sort method also has two optional arguments: key and reverse

1. When the key is used, it must provide a function that is always called by the sorting process:


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

2. For reverse to implement descending sort, it is necessary to provide a Boolean value:


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


Related articles: