python:sort,sorted,ordereddict Usage – May 13, 2011 20:58 from http://stqdd.com/archives/427 by Moya Dish
Python has two kinds of data in the container, one is the container's own sort function, one is the built-in sorted function.
The only difference between the sort function and the sorted function is that sort is sorted within the container, sorted generates a new ordered container.
For a simple array of l=[5,2,3,1,4].
Sort:l.sort ()
Sorted (...)
Sorted (iterable, Cmp=none, Key=none, Reverse=false)--> new sorted list
Iterable: An iterative type of container to be sorted;
CMP: A function For comparison, comparing what is determined by the key, having a default value, and an item in the iteration set;
Key: Use a named property or function of a list element (with only one parameter and return a value for sorting) as a keyword, with a default value, an item in the iteration set;
Reverse: Sorting rules. Reverse = True or reverse = False, with default values.
Return value: Is a sorted, iterative type, similar to iterable.
If it is a multidimensional list l=[(' B ', 2), (' A ', 1), (' C ', 3), (' d ', 4)].
There are three options for sorting this multidimensional list using CMP functions
Sorted (L, Cmp=lambda x,y:cmp (x[1],y[1))
L.sort (Cmp=lambda x,y:cmp (x[1],y[1)) utilizes key
Sorted (L, Key=lambda x:x[1]);
L.sort (Key=lambda x:x[1]); Reverse order
The above sorts all can add parameter reverse.
For example sorted (reverse=true), L.sort (reverse=true). or change it to false.
Ordereddict is a package in collections that can record the order in which dictionary elements are inserted, often used with sort functions to generate a sorted dictionary.
For example, an unordered dictionary.
D = {' Banana ': 3, ' Apple ': 4, ' pear ': 1, ' Orange ': 2}
By sorting to generate an ordered dictionary, there are several ways
Collections. Ordereddict (Sorted (D.items (), key = Lambda t:t[0))
Or
Collections. Ordereddict (Sorted (D.items (), key = Lambda t:t[1))
Or
Collections. Ordereddict (Sorted (D.items (), key = Lambda T:len (t[0)))