operator module and module functools

operator module
In functional programming, often you need to use as a function arithmetic operators. For example, the recursive computation is not used factorial. Summing sum function may be used, but there is no such a quadrature function. We can use the reduce function (section 5.2.1 is to do so), but requires a function to calculate the product of two elements of the sequence. Example 5-21 shows how to use a lambda expression to solve this problem.
  Example 5-21 factorial calculation function and reduce the use of an anonymous function
from functools import reduce
def fact(n):
    return reduce(lambda a, b: a*b, range(1, n+1))
operator module provides a function corresponding to the plurality of arithmetic operators, in order to avoid the preparation of lambda a, b: a * b this lowly anonymous function. Functions using arithmetic operators, can be rewritten as in Example 5-22 Example 5-21 above.
   Example 5-22 and reduce operator.mul function factorial
from functools import reduce
from operator import mul
def fact(n):
    return reduce(mul, range(1, n+1))
operator module there is a class function, lambda expressions can replace an element taken from the sequence object to be read or properties: Thus, itemgetter attrgetter fact and builds its own function.
Example 5-23 shows a common use of itemgetter of: tuples to sort the list according to a field tuple. In this example, the print order information of each city country code (second field). In fact, the role of itemgetter (1) and lambda fields: fields [1] the same: to create a set of accepted function returns the element 1 on the index bits. Example 5-23 demonstrates use itemgetter sort a list of tuples (data from Example 2-8)
metro_data = [
    ('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
    ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
    ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
    ('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
    ('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
 ]

from operator import itemgetter
for city in sorted(metro_data, key=itemgetter(1)):
    print(city)
If the plurality of parameters passed itemgetter, it builds the function will return the value of the extracted tuple consisting of:
 

Guess you like

Origin www.cnblogs.com/xiangxiaolin/p/11609324.html