Two methods and examples of python list sorting

Python provides two methods for sorting lists

Method 1. Use the built-in function list.sort of List to sort

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

Python instance:

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

Method 2. Sorting with the sequence type function sorted(list)

Python instance:

>>> 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 does not change. A new ordered list object is generated.

list.sort() does not return objects, changing the original list.
Other sort instances:

Example 1: forward sort

>>>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: sorting the second key

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

Example 4: sorting the second key

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

Example 5: sorting the second key

>>>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 undercorporate)

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

The above gives the method of sorting List in 6, in which example 3.4.5.6 can play a role in sorting a List item

Sort the comparison keywords

Efficiency comparison:

cmp < DSU < key

Method 3 is slower than method 6, method 6 is slower than method 4, and method 4 and method 5 are basically the same

Multi key comparison and sorting:

Example 7:

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

We can see that the sorted L is only arranged according to the second keyword,

What if we want to sort by the second keyword and then 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[1],x[0]))
>>> L
>>>[('c', 2), ('d', 2), ('b', 3), ('a', 4)]

Example 9:

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

Why does instance 8 work? The reason is that tuple compares from left to right. After comparing the first one, if it is equal, compare the second one

Tags: Python Lambda

Posted on Sun, 10 Nov 2019 06:06:32 -0800 by pixelgirl