In-depth Python (1): dictionary sorting about sort (), reversed (), sorted (), reversedsorted

Source: Internet
Author: User

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 numbersli = sorted(lis, key=lambda s: s['Big']) # Output:#[{'small': 1, 'Big': 1}, {'small': 2, 'Big': 2}, {'small': 1, 'Big': 2}, {'small': 2, 'Big': 3}, {'small': 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.

 

==============================================

 

    1. #-*-Encoding = UTF-8 -*-
    2. Import operator
    3. # Sort by dictionary values (Ascending by default)
    4. X =}
    5. Sorted_x = sorted (x. iteritems (), key = operator. itemgetter (1 ))
    6. Print sorted_x
    7. # [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
    8. # If you want to sort data in descending order, you can specify reverse = True
    9. Sorted_x = sorted (x. iteritems (), key = operator. itemgetter (1), reverse = True)
    10. Print sorted_x
    11. # [(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
    12. # Or directly use the list reverse Method to reverse sorted_x order
    13. # Sorted_x.reverse ()
    14. # The replacement method is to use a lambda expression
    15. Sorted_x = sorted (x. iteritems (), key = lambda x: x [1])
    16. Print sorted_x
    17. # [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
    18. Sorted_x = sorted (x. iteritems (), key = lambda x: x [1], reverse = True)
    19. Print sorted_x
    20. # [(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
    21. # The sorting method of the list containing the dictionary dict is similar to that of dict, as follows:
    22. X = [{'name': 'Homer', 'age': 39}, {'name': 'bart', 'age': 10}]
    23. Sorted_x = sorted (x, key = operator. itemgetter ('name '))
    24. Print sorted_x
    25. # [{'Age': 10, 'name': 'bart'}, {'age': 39, 'name': 'Homer'}]
    26. Sorted_x = sorted (x, key = operator. itemgetter ('name'), reverse = True)
    27. Print sorted_x
    28. # [{'Age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'bart'}]
    29. Sorted_x = sorted (x, key = lambda x: x ['name'])
    30. Print sorted_x
    31. # [{'Age': 10, 'name': 'bart'}, {'age': 39, 'name': 'Homer'}]
    32. Sorted_x = sorted (x, key = lambda x: x ['name'], reverse = True)
    33. Print sorted_x
    34. # [{'Age': 39, 'name': 'Homer'}, {'age': 10, 'name': 'bart'}]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.