Python has a very handy and efficient sorting function, and here's how to sort list,dict sort/sorted.
1. Sort the second value in list of tuples with list.sort/sorted
>>> Import operator>>> a=[(' A ', 3), (' B ', 2), (' C ', 1)]>>> import operator>>> l=[(' a ' , 3), (' B ', 2), (' C ', 1)]>>> L.sort (Key=operator.itemgetter (1)) >>> l[(' C ', 1), (' B ', 2), (' A ', 3)]> >> sorted (L, Key=operator.itemgetter (1)) [(' C ', 1), (' B ', 2), (' A ', 3)]>>> sorted (L, key= Operator.itemgetter (0)) [(' A ', 3), (' B ', 2), (' C ', 1)]
The difference between list.sort and sorted: Sort is a method of the list sequence, and sorted is a built-in function
List.sort: There is no return value, and sort is the inner function of the sequence, and the called sequence is sorted after the call is finished
Sorted: The function does not change the parameters and returns the ordered copy of the sequence
The sort and sorted are described in detail in the Python development documentation, or you can call the Help function to see the difference between the two
>>> help (List.sort)-on Method_descriptor:sort (...) L.sort (Key=none, Reverse=false), None--stable sort *in place*
>>> help (sorted) to built-in/, *, Key=none, reverse=False) from inch ascending order. and the in descending order.
2. In addition to using operator, we can also use lambda
>>> L.sort (key=Lambda x:x[1])>>> l[('C', 1 ), ('b', 2), ('a', 3)]
3. Use sorted to sort the ditionary
>>> L = {' A ': 3, ' B ': 2, ' C ': 1}>>> Sl_key = sorted (L.items ()) #Sort by key>>> sl_key[(' A ', 3 ), (' B ', 2), (' C ', 1)]>>> Sl_value = sorted (L.items (), Key=lambda x:x[1]) #Sort by value>>> Sl_value [(' C ', 1), (' B ', 2), (' A ', 3)]>>> Sl_value = sorted (L.items (), Key=lambda x:x[1], reverse=true) #Sort by value Backwards>>> sl_value[(' A ', 3), (' B ', 2), (' C ', 1)]>>> Sl_value = sorted (L.items (), Key=lambda x: (X[1], X[0]), reverse=true) #Sort by value then by Key>>> sl_value[(' A ', 3), (' B ', 2), (' C ', 1)]
Python Learning--operator.itemgetter (), list.sort/sorted, and lambda functions