Python's internal container, probably divided into: tuple,set,list,dict, in order to sort, the list and Dictionary of the Order of more requirements, tuple mainly as an immutable container, set to repeat, the following list and dict common sorting methods summarized:
First, List
1, list sorting is very simple, mainly see the list of elements, if the element is composed of single values, such as the following method:
>>> a = [1,2,5,3,4]>>> a.sort () >>> print a[1, 2, 3, 4, 5]
The list itself comes with the sort () method, which operates on the list itself, which means that the original structure of a is changed.
2. The list element is made up of tuples, which require a column of tuples to be sorted, as shown in the following example:
Using Python's built-in function, sorted (), obviously put the sorting results in the B list, but it doesn't actually change the original structure of the A data, if we still use the sort () method of the list? Examples are as follows:
There is one more way to do this, but use the CMP parameter:
CMP is a comparison, x[1],y[1] represents the second column of the first and second elements, reverse=0 means no inversion, can reverse=false, the same effect, of course, reverse can not write, the default is False
3. Using operator module
>>> a[(' C ', 1), (' B ', 2), (' A ', 3)]>>> B = Sorted (A,key=itemgetter (0)) >>> b[(' A ', 3), (' B ', 2), (' C ', 1)]
Second, the dictionary sort
Dictionary, the main thing is to sort by key or value.
There are ways to do it directly with a for loop, but I think direct sorted () is clear.
Summarize:
Generally do sort, list can be based on whether to change the original data structure to choose different methods, the dictionary with sorted can, about efficiency, in fact, I personally feel the key method with lambda faster.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Python sort, for list, dictionary