I would like to B = {' a ': 234, ' b ': 1, ' C ': 2, ' e ': 2387} sorted by key and value, what should I do?
The more commonly used sort in python has two functions,
first, the definition
(1) One is the sort in the list data structure
>>> Help (list.sort)
Help on Method_descriptor:
Sort (...)
L.sort (cmp=none, key=none, reverse=false)-stable sort *in place*;
CMP (x, y)-1, 0, 1
The sort () method takes optional arguments for controlling the Comparisons.
CMP Specifies a custom comparison function of arguments (list Items) which should return a negative, zero or Positive number depending on whether the first argument are considered smaller than, equal to, or larger than the second AR Gument: cmp=lambda x, y:cmp (x.lower (), y.lower ()). The default value is None.
key Specifies a function of one argument That's used to extract a comparison key from each list element: key =str.lower. The default value is None.
Reverse is a Boolean Value. If set to True, then the list elements is sorted as if each comparison were reversed.
In general, the key and reverse conversion processes is much faster than specifying an equivalent C MP Function. This is because CMPare called multiple times for each list element while key and reverse touch E The ACH element is only once. Use functools.cmp_to_key () to convert the Old-style CMP function to a key Function.
Changed in version 2.3:support for None as a equivalent to omitting CMP is Added.
Changed in version 2.4:support for key and reverse is Added.
(2) built-in function sorted
Sorted (iterable[, cmp[, key[, reverse] ] )
Return a new sorted list from the items in iterable.
Indicates that the built-in sorted function generates a new data table without altering the order of the original Data.
The optional arguments CMP, key, and reverse has the same meaning as those for the List.sort () method (described in sectionMutable Sequence Types).
CMP Specifies a custom comparison function of the arguments (iterable elements) which should return a negative, Z Ero or positive number depending on whether the first argument are considered smaller than, equal to, or larger than the SE Cond argument:cmp=lambda x, y: cmp (x.lower (), y.lower ()). The default value is None.
key Specifies a function of one argument That's used to extract a comparison key from each list element: key =str.lower. The default value is None (compare the elements directly).
Reverse is a Boolean Value. If set to True, then the list elements is sorted as if each comparison were reversed.
In general, the key and reverse conversion processes is much faster than specifying an equivalent C MP Function. This is becauseCMP are called multiple times for each list element while key and reverse touch E The ACH element is only once. Use functools.cmp_to_key () to convert the Old-style CMP function to a key Function.
Ii. examples
Sorting Basics
>>>sorted ([5, 2, 3, 1, 4])[1, 2, 3, 4, 5]
>>> a = [5, 2, 3, 1, 4]>>> a.sort ()>>> a[1, 2, 3, 4, 5]
sorted () -but If you don ' t need the original list, it's slightly more Efficient. (although The first method is not very convenient, but usually more efficient)
>>> sorted ({1: ' D ', 2: ' b ', 3: ' b ', 4: ' E ', 5: ' A '})[1, 2, 3, 4, 5]
Another difference is, the list.sort () method is only defined for Lists. In contrast, the sorted () function accepts any iterable.
(another Point is that the List.sort () method can only be used as the data structure of a list, however, sorted is available as any data structures that can be iterated)
Key Functions
Starting with Python 2.4, both list.sort () and sorted () added a key parameter to specify a func tion to is called on every list element prior to making comparisons (since 2.4, the new key parameter has been added, by making a judgment function to sort by key)
>>> Sorted ("this was a test string from Andrew". split (), key=str.lower)[' a ', ' Andrew ', ' from ', ' is ', ' string ', ' Test ', ' this ']
>>> student_tuples = [ (' John ', ' A ', '), (' Jane ', ' b ', '), (' Dave ', ' b ', ten), " >>> sorted (student_tuples, key=lambda student:student[2]) # Sort by age[(' Dave ', ' b ', ten), (' Jane ', ' b ', (' John ', ' A ', 15)]
Lambda function parameter: return value
>>> class Student: Self.name = NAME
Self.grade = Grade
Self.age = Age def __repr__ (self): return repr ((self.name, self.grade, self.age)) def Weighted_grade (self): return ' CBA '. index (self.grade)/float (self.age) < Span class= "anchor" >>>> student_objects = [ student (' John ', ' A ', 15), Student (' Jane ', ' b ', '), Student (' Dave ', ' b ', ten), >>> sorted (student_objects, key=lambda Student:student.age) # Sort by Age[(' Dave ', ' b ', ten), (' Jane ', ' b ', '), (' John ', ' A ', ')]
span>
Operator Module Functions
The key-function patterns shown above be very common, so Python provides convenience functions to make accessor functions Easier and Faster. The operator module has itemgetter, Attrgetter, and starting in Python 2.6 a methodcaller funct Ion.
Using those functions, the above examples become simpler and faster.
With the introduction of the operator module there is a quicker way to query:
>>> from operator import itemgetter, attrgetter, methodcaller>>> sorted (student_tuples, key= Itemgetter (2)) [(' Dave ', ' b ', ten), (' Jane ', ' b ', '), (' John ', ' A ', ')]>>> sorted (student_objects, key= Attrgetter (' age '))[(' Dave ', ' b ', ten), (' Jane ', ' b ', '), (' John ', ' A ', ')]
The operator module functions allow multiple levels of sorting. For example, To-sort by grade-by-age:
(we can not only sort by a condition, we can also set multiple criteria to sort, as in the following example, according to the class, in accordance with the Age)
>>> sorted (student_tuples, key=itemgetter)[(' John ', ' A ', '), (' Dave ', ' b ', ten), (' Jane ', ' b ', 12)] >>> sorted (student_objects, key=attrgetter (' grade ', ' age '))[(' John ', ' A ', '), (' Dave ', ' B ', 10), (' Jane ', ' B ', ')]
Ascending and descending (ascending order)
Just add a reverse to the BACK.
>>> sorted (student_tuples, key=itemgetter (2), Reverse=true)[(' John ', ' A ', '), (' Jane ', ' B ', '), (' Dave ', ' B ', ten)]>>> sorted (student_objects, key=attrgetter (' age '), Reverse=true)[(' John ', ' A ', 15), (' Jane ', ' b ', (), (' Dave ', ' b ', 10)]
Going back to where we started, we can easily write:
Import operator
def sortdict ():
b = {' a ': 234, ' b ': 1, ' C ': 2, ' e ': 2387}
Print (sorted (b.iteritems (), key=operator.itemgetter (0)) #按key升序排列
Print (sorted (b.iteritems (), key=operator.itemgetter (1)) #按value升序排列
Print (sorted (b.items (), key=lambda X:x[1],reverse=true)) # #按value降序排列
Output result:
[(' a ', 234), (' b ', 1), (' c ', 2), (' e ', 2387)]
[(' b ', 1), (' c ', 2), (' a ', 234), (' e ', 2387)]
[(' e ', 2387), (' a ', 234), (' c ', 2), (' b ', 1)]
Dictionary ordering in Python