In-depth Python (1): dictionary sorting about sort (), reversed (), sorted (), reversedsorted
Http://www.cnblogs.com/BeginMan/p/3193081.html
I. Sorting of Python
1. reversed ()
This is easy to understand. The reversed clause is reverse.
print list(reversed(['dream','a','have','I']))#['I', 'have', 'a', 'dream']
2. Confusing sort () and sorted ()
In Python, sorted is a built-in function (BIF), while sort () is a list-type built-in function list. sort ().
Sorted ()
- Sorted (Iterable [, cmp [, key [, reverse] )
-
Return a new sorted list from the items in iterable.
The optional arguments (optional) cmp, key, and reverse have the same meaning as those forList. sort ()Method (described in section Mutable Sequence Types ).
Cmp specifies (specified) a custom comparison function of two arguments (iterable (iteratable) elements) which shocould return a negative (plural), zero or positive (positive) number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument:Cmp = lambda x, y: cmp (x. lower (), y. lower ()). The default value isNone.
Key specifies a function of one argument that is used to extract a comparison key from each list element:Key = str. lower. The default value isNone(Compare the elements directly ).
Reverse is a boolean value. If setTrue, Then the list elements are sorted as if each comparison were reversed.
# String sorting uses the Lexicographic Order instead of the alphabetic order "" sorted () "" lis = ['A', 'C', 'z ', 'E', 't', 'C', 'B', 'A', 'A', 'good', 'tack'] print sorted (lis) # ['A ', 'C', 'E', 'good', 't', 'tack', 'A', 'B', 'C', 'z']
Lexicographic Order:
Refer to Baidu encyclopedia. Http://baike.baidu.com/view/4670107.htm
Based on the ASCII sorting, the details are as follows:
0-9 (corresponding to the value 48-59 );
A-Z (corresponding to the value 65-90 );
A-z (corresponding to the value 97-122 );
------------Standard Order: numbers are equal to and later than letters,
For example, to <up <cap <cat <too <two <boat <boot <card
Lexicographic Order: sequential ratio of letters,
For example, boat <boot <cap <card <cat <to <too <two <up
Even more, the Lexicographic Order is the sort of the dictionary, just like the dictionary. I have never found an authoritative explanation. What is the Lexicographic Order ???? Please answer !!
Sort ()
S. sort ([cmp [, key [, reverse])
Iii. Python dictionary sorting
1. Python dictionary features
Unordered:
Dictionary, such as dic = {'A': 1, 'B': 2, 'C': 3}. The elements in the dictionary have no order, therefore, dic [0] has a syntax error.
No weight:
Duplicate key values are not allowed, so dic. after adding ['C'] = 4, the dictionary becomes {'A': 1, 'B': 2, 'C': 4 }.
2. sort by "key" or "key value" in different order
Function prototype: sorted (dic, value, reverse)
Explanation:Dic is a comparison function, and value is the sorting object (key or key value here ),
Reverse: indicates whether the values are in ascending or descending order. True indicates in descending order, and False indicates in ascending order (default)
3. Example:
Dic = {'A': 31, 'bc': 5, 'C': 3, 'asd ': 4, '33': 56, 'D': 0}
Sort the dic values in ascending order (values are integers ).
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, '33':56, 'd':0}print sorted(dic.iteritems(), key=lambda d:d[1], reverse = False ) #[('d', 0), ('c', 3), ('asd', 4), ('bc', 5), ('a', 31), ('33', 56)]
Explanation:
(1) dic. iteritems (), return the ancestor set of the dictionary key-Value Pair
print dic.iteritems() #<dictionary-itemiterator object at 0x00B71A80>for obj in dic.iteritems(): print obj,obj[0],obj[1] #('a', 31) a 31#('c', 3) c 3#('d', 0) d 0#('bc', 5) bc 5#('33', 56) 33 56#('asd', 4) asd 4
(2) sorting objects
As mentioned above, value (or key) is the sort object (here it refers to the key or key value). However, why use lambda functions? See:Click to read
Key = lambda d: d [1] uses the key value (value) as the sorting object.
Key = lambda d: d [1] for I in dic. iteritems (): print key (I), # output 31 3 0 5 56 4, these are the dictionary dic values
If you select key = lambda d: d [0], select Key key as the sorting object.
(3), reverse
Whether or not the reverse is reverse. reverse = Ture indicates reverse.
(4) Note:
Sorted (dic. iteritems (), key = lambda d: d [1], reverse = False) convert each item into dic. the original of the iteritems () key-value pair is iterated. each item is passed into the key () function as a parameter (I am talking about this: key = lambda d: d [1],).
4. Review
lis = ['a','bc','c','asd','33','d']print sorted(lis) #['33', 'a', 'asd', 'bc', 'c', 'd']
Match letters in sequence, such as boat <boot <cap <card <to <too <two <up
5. Problems
For specific examples, refer to [** python sorting function sort, sorted in list sorting and dictionary sorting application details and examples **] (http://wangwei007.blog.51cto.com/68019/1100742)
In this case, sort in order. For example, sort the question numbers and then sort the question numbers as follows:
1234567891011121314151617181920212223 |
lis = [{ 'Big' : 3 , 'small' : 2 },{ 'Big' : 3 , 'small' : 4 },{ 'Big' : 2 , 'small' : 2 }, { 'Big' : 3 , 'small' : 1 },{ 'Big' : 2 , 'small' : 1 },{ 'Big' : 1 , 'small' : 1 }] # Sorting of question numbers li = sorted (lis, key = lambda s: s[ 'Big' ]) # Output: #[{'small': 1, 'Big': 1}, {'small': 2, 'Big': 2}, {'small': 1, 'Big': 2}, {'small': 2, 'Big': 3}, {'s mall ': 4, ' Big ': 3}, {' small ': 1, ' Big': 3 }] # Sorting of question numbers: sort_ff = [] no = set ([i[ 'Big' ] for i in li]) for obj in no: li_ = [] for i in ff: if i[ 'Big' ] = = obj: li_.append(i) l = sorted (li_, key = lambda s: s[ 'small' ]) for j in l: sort_ff.append(j) # Output result: [{ 'small' : 1 , 'Big' : 1 }, { 'small' : 1 , 'Big' : 2 }, { 'small' : 2 , 'Big' : 2 }, { 'small' : 1 , 'Big' : 3 }, { 'small' : 2 , 'Big' : 3 }, { 'small' : 4 , 'Big' : 3 }] |
Make good use of sort () or sorted (). a. sort () has changed its structure, and B = a. sort () is a wrong way! Sorted (a,...) does not change the structure of.
==============================================
- #-*-Encoding = UTF-8 -*-
- Import operator
- # Sort by dictionary values (Ascending by default)
- X =}
- Sorted_x = sorted (x. iteritems (), key = operator. itemgetter (1 ))
- Print sorted_x
- # [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
- # If you want to sort data in descending order, you can specify reverse = True
- Sorted_x = sorted (x. iteritems (), key = operator. itemgetter (1), reverse = True)
- Print sorted_x
- # [(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
- # Or directly use the list reverse Method to reverse sorted_x order
- # Sorted_x.reverse ()
- # The replacement method is to use a lambda expression
- Sorted_x = sorted (x. iteritems (), key = lambda x: x [1])
- Print sorted_x
- # [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
- Sorted_x = sorted (x. iteritems (), key = lambda x: x [1], reverse = True)
- Print sorted_x
- # [(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
- # The sorting method of the list containing the dictionary dict is similar to that of dict, as follows:
- X = [{'name': 'Homer', 'age': 39}, {'name': 'bart', 'age': 10}]
- Sorted_x = sorted (x, key = operator. itemgetter ('name '))
- Print sorted_x
- # [{'Age': 10, 'name': 'bart'}, {'age': 39, 'name': 'Homer'}]
- Sorted_x = sorted (x, key = operator. itemgetter ('name'), reverse = True)
- Print sorted_x
- # [{'Age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'bart'}]
- Sorted_x = sorted (x, key = lambda x: x ['name'])
- Print sorted_x
- # [{'Age': 10, 'name': 'bart'}, {'age': 39, 'name': 'Homer'}]
- Sorted_x = sorted (x, key = lambda x: x ['name'], reverse = True)
- Print sorted_x
- # [{'Age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'bart'}]