python: A simple way to sort list
- 2021-08-17 00:34:37
- OfStack
Have you found that when searching on the website and entering one keyword for the content you want to find, the keyword extension and problems will appear under the search column? The more keywords you enter, the more likely you are to find the question you want. In fact, this situation is due to the sorting of computer algorithms, which will be sorted according to keyword association, search volume and other reasons. Do you know how to sort lists in python? Today, this site teaches you how to sort lists.
sort () method
The elements in list are sorted by size
list.sort(key=None,reverse=False)
Example:
In [57]: l=[27,47,3,42,19,9]
In [58]: l.sort()
In [59]: l
Out[59]: [3, 9, 19, 27, 42, 47]
sorted () method
It is mainly used for assigning values
In [62]: l=[27,47,3,42,19,9]
In [63]: sorted(l)
Out[63]: [3, 9, 19, 27, 42, 47]
Note:
The sort () method does not return an object, changing the original list.
The sorted () method returns 1 object, which can be used as an expression. The original list is unchanged, and a new ordered list object is generated.
Instance extension:
Forward sort
>>>L = [2,3,1,4]
>>>L.sort()
>>>L
>>>[1,2,3,4]
Reverse sort
>>>L = [2,3,1,4]
>>>L.sort(reverse=True)
>>>L
>>>[4,3,2,1]