List sorting in Python, given a list and sorted in ascending or descending order (Section 1)

2022-05-20 0 By

We often encounter a lot of unordered numbers in life, sometimes in order to make the results more intuitive, often need to sort these unordered numbers in ascending or descending order, so today, also happens to be the first part of the Python review, so we will talk about how to use Python language to implement list sorting.Table L=[4,2,25,777777,100,3]Combing through the logic, it can be found that given a set of arrays L=[4,2,25, 77777777,100,3], the ascending and descending results are [2,3,4,25,100,7777777] and [77777777,100,25,4,32,2] respectively.For Python, there are two ways to implement ascending and descending order. The first is the traditional method, which compares the given data in pairs and swaps places, similar to bubble sort.The second method is to use Python’s native sort function directly, which is used for sorting. Its syntax is l.sort (CMP =None,key=None,reverse=False).CMP represents an optional parameter, key represents the element to be compared, and reverse represents the collation rule.Traditional method code implementation #!/usr/bin/python3l =[4,2,25,777777,100,3]Temp = 0for I in range(len(L)): for j in range(0,len(L)-1): if L[j]>L[j+1]: Temp = L[j+1] L[j] L[j] L = Tempprint(L) Temp = L[j+1] L[j] L[j] L = LYou only need to modify the L[j]sort method code to implement #!/usr/bin/python3l =[4,2,25,777777,100,3] l.port (reverse=True)print(L)All in all, The Python syntax is relatively simple, and there are already formable functions to use, such as sorting, which can be done directly by using the sort method.