Detailed explanation of sorted usage of python

  • 2021-07-01 07:46:20
  • OfStack

The list has its own sort method, which sorts the list in-situ. Since it is in-situ sorting, it is obviously impossible for tuples to have this method, because tuples are unmodifiable.

Sorting, numbers and strings are sorted from small to large according to ASCII, and Chinese is sorted from small to large according to unicode


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 can you do 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 the list x to y by slicing operation. If x is simply assigned to y: y = x, y and x still point to the same list, and no new copy is generated.

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 types are always listed, as follows:


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

# 2. Have 1 A list['This','is','a','Boy','!'], All elements are strings, which are sorted case-independent 
li=['This','is','a','Boy','!']
l=[i.lower() for i in li]
# l1 =l[:]
l.sort() #  Sort the original list with no return value 
print(l)
# print(sorted(l1))  #  The original list with return values has not changed 
# print(l1)

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

1. When key is used, it must provide 1 function called by the sorting procedure:


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

2. reverse realizes descending sorting, and needs to provide a Boolean value:


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

True is arranged in reverse order and False is arranged in positive order


Related articles: