To sort the list, Python provides two methods
---sort----
Method 1. Sorting using the List.sort function of list
List.sort (Func=none, Key=none, Reverse=false)
Method 2. Sort by sequence type function sorted (list)
>>> list = [2,5,1]
>>> list
[2, 5, 1]
>>> sorted (list)
[1, 2, 5]
> >> list
[2, 5, 1]
>>> list.sort ()
>>> list
[1, 2, 5]
Sorted (list) Returns an object that can be used as an expression. The original list does not change, creating a new sorted list object.
List.sort () does not return the object, changing the original list.
Example 1:
>>>l = [2,3,1,4]
>>>l.sort ()
>>>l
>>>[1,2,3,4]
Example 2:
>>>l = [2,3,1,4]
>>>l.sort (Reverse=true)
>>>l
>>>[4,3,2,1]
Sort the Second keyword:
Example 3:
>>>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)]
>>>l = [(' B ', 2), (' A ', 1), (' C ', 3), (' d ', 4)]
Example 4:
>>>import operator
>>>l.sort (Key=operator.itemgetter (1))
>>>l
>>>[(' A ', 1), (' B ', 2), (' C ', 3), (' d ', 4)]
(operator module for detailed usage please take part in the previous blog.) )
What if we want to order the second keyword and then sort it with the first keyword? There are two ways
Example 5:
>>> 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 6:
>>> 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)]