# Two methods and examples of python list sorting

• 2020-05-27 06:02:02
• OfStack

Sort List, and Python provides two methods

Method 1. Sort with List's built-in function list.sort

list.sort(func=None, key=None, reverse=False)

Python instances:

``````
>>> list = [2,5,8,9,3]
>>> list
[2,5,8,9,3]
>>> list.sort()
>>> list
[2, 3, 5, 8, 9]``````

Method 2. Sort with the sequence type function sorted(list) (starting at 2.4)

Python instances:

``````
>>> list = [2,5,8,9,3]
>>> list
[2,5,8,9,3]
>>> sorted(list)
[2, 3, 5, 8, 9]``````

Differences between the two methods:

sorted(list) returns an object that can be used as an expression. The original list is unchanged, and a new ordered list object is generated.

list.sort () does not return the object, changing the original list.

Other examples of sort:

Example 1: forward sorting

``````
>>>L = [2,3,1,4]
>>>L.sort()
>>>L
>>>[1,2,3,4]``````

Example 2: reverse sort

``````
>>>L = [2,3,1,4]
>>>L.sort(reverse=True)
>>>L
>>>[4,3,2,1]``````

Example 3: sort the second keyword

``````
>>>L = [('b',6),('a',1),('c',3),('d',4)]
>>>L.sort(lambda x,y:cmp(x,y))
>>>L
>>>[('a', 1), ('c', 3), ('d', 4), ('b', 6)]``````

Example 4: sort the second keyword

``````
>>>L = [('b',6),('a',1),('c',3),('d',4)]
>>>L.sort(key=lambda x:x)
>>>L
>>>[('a', 1), ('c', 3), ('d', 4), ('b', 6)]``````

Example 5: sort the second keyword

``````
>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>import operator
>>>L.sort(key=operator.itemgetter(1))
>>>L
>>>[('a', 1), ('b', 2), ('c', 3), ('d', 4)]``````

Example 6:(DSU method: Decorate-Sort-Undercorate)

``````
>>>L = [('b',2),('a',1),('c',3),('d',4)]
>>>A = [(x,i,x) for i,x in enumerate(L)] #i can confirm the stable sort
>>>A.sort()
>>>L = [s for s in A]
>>>L
>>>[('a', 1), ('b', 2), ('c', 3), ('d', 4)]``````

The sorting method of List in 6 is given above, in which example 3.4.5.6 can pair one item in List item

Sort the comparison keywords.

Efficiency comparison:

cmp < DSU < key

Through experimental comparison, method 3 is slower than method 6, and method 6 is slower than method 4. Method 4 and method 5 are basically the same

Multi-keyword comparison sorting:

Example 7:

``````
>>>L = [('d',2),('a',4),('b',3),('c',2)]
>>> L.sort(key=lambda x:x)
>>> L
>>>[('d', 2), ('c', 2), ('b', 3), ('a', 4)]``````

As we can see, the ordered L is only sorted by the second keyword,

What if we want to sort by the second keyword and then sort by the first keyword? There are two ways

Example 8:

``````
>>> L = [('d',2),('a',4),('b',3),('c',2)]
>>> L.sort(key=lambda x:(x,x))
>>> L
>>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)]``````

Example 9:

``````
>>> list = [2,5,8,9,3]
>>> list
[2,5,8,9,3]
>>> sorted(list)
[2, 3, 5, 8, 9]``````
0

Why does example 8 work? The reason is that tuple compares left to right, compares the first, and if they're equal, compares the second

Related articles: