Operator.itemgetter function
The Itemgetter function provided by the operator module is used to get the data of which dimensions of the object, with some ordinal numbers (that is, the number of the data that needs to be fetched in the object), as shown in the example below.
A = [A]
>>> B=operator.itemgetter (1)//define function B, get the value of the 1th field of an object
>>> B (a)
2
>>> B=operator.itemgetter (1,0)//define function B, get the 1th field and No. 0 value of an object
>>> B (a)
(2, 1)
Note that the Operator.itemgetter function does not get a value, but instead defines a function that acts on the object to get the value.
Sorted function
Python's built-in sorting function sorted can be sorted on list or iterator, on official website: http://docs.python.org/2/library/functions.html?highlight= Sorted#sorted, the function prototype is:
Sorted (iterable[, CMP[, Key[, reverse]]])
Parameter explanation:
(1) iterable specifies the list or iterable to sort, not to mention;
(2) CMP is a function that specifies a function to compare when sorting, you can specify a function or a lambda function, such as:
Students is a list of class objects, no member has three fields, you can set the CMP function by comparing it with sorted, for example, by comparing the third data member, the code can write: students = [(' John ', ' A ', '), (' Jane ', ' B ', '), (' Dave ', ' B ', ten)] sorted (students, KEY=LAMBDA Student:student[2]) (3) key is a function that specifies which item of the element to sort by, and the function uses the above example To illustrate, the code is as follows: sorted (students, KEY=LAMBDA student:student[2]) key specifies the function of the lambda function is to go to the third domain of the element student (i.e.: student[2]), so When sorted is sorted, it is sorted with the third field of all elements students. With the Operator.itemgetter function above, you can also use this function, for example, to sort by student's third field, you can write: sorted (students, Key=operator.itemgetter (2)) The sorted function can also be ordered in multiple levels, for example, to sort on the second and third fields, so write: sorted (students, Key=operator.itemgetter)
That is, sort the second field first, and then sort by the third field. (4) The reverse parameter does not have to say more, is a bool variable, indicating ascending or descending order, the default is False (ascending order), when defined as true will be sorted in descending order.
More examples of sorted functions can be found in the official website documentation: https://wiki.python.org/moin/HowTo/Sorting/.
Sorted functions in Python and Operator.itemgetter functions