Python learns Day 5 high-level functions map/reduce filter sorter return functions anonymous function decorators partial functions, pythonsorter
Higher-orderfunction
Variable can point to function
>>> Abs # abs (-10) is a function call, while abs is the function itself.
<Built-in function abs>
>>> F = abs # the function itself can also assign values to variables.
>>> F # variables can point to functions.
<Built-in function abs>
>>> F (-10) # variable call Function
10
The function name is also a variable.
>>> Abs = 10
>>> Abs (-10) # This function cannot be called through abs (-10) after abs is pointed to 10
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Input Function
Since variables can point to functions and function parameters can receive variables, one function can receive another function as a parameter, which is called a higher-order function.
>>> Def add (x, y, f ):
Return f (x) + f (y)
>>> Add (-1,-2, abs)
Map
The map () function receives two parameters. One is a function, and the other is a sequence. map sequentially applies the input function to each element of the sequence and returns the result as a new list. For example, if we have a function f (x) = x2, we need to apply this function to a list [1, 2, 3, 4, 5, 6, 7, 8, 9], you can use map () to implement the following:
>>> Def f (x ):
Return x * x
>>> Map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # The first parameter is f, that is, the function object itself.
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> Map (str, [1, 2, 3, 4, 5, 6, 7, 8, 9]) # convert all the numbers in the list into strings
['1', '2', '3', '4', '5', '6', '7', '8', '9']
Reduce (...)
Reduce (function, sequence [, initial])-> value
Apply a function of two arguments cumulatively to the items of asequence, from left to right, so as to reduce the sequence to a single value.
For example, reduce (lambda x, y: x + y, [1, 2, 3, 4, 5]) calculates (1 + 2) + 3) + 4) + 5 ). if initial ispresent, it is placed before the items of the sequence in the calculation, and serves as a default whenthe sequence is empty.
>>> Def add (x, y ):
Return x + y
>>> Reduce (add, [1, 3, 5, 7, 9])
25
Def str2int (s): # convert str to str2int
Def fn (x, y ):
Return x * 10 + y
Def char2num (s ):
Return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} [s]
Return reduce (fn, map (char2num, s ))
Filter
Filter (...)
Filter (function or None, sequence)-> list, tuple, or string
Return those items of sequence for which function (item) is true. If
Function is None, return the items that are true. If sequence is a tuple
Or string, return the same type, else return a list.
Def is_odd (n): # Delete the even number in list
Return n % 2 = 1
Filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15])
Def not_empty (s): # delete an empty string from the sequence
Return s and s. strip ()
Filter (not_empty, ['A', '', 'B', None, 'C',''])
Sorted
Sorted (iterable, cmp = None, key = None, reverse = False) --> new sorted list
>>> Def reversed_cmp (x, y): # reverse sorting
If x> y:
Return-1
If x <y:
Return 1
Return 0
>>> Sorted ([36, 5, 12, 9, 21], reversed_cmp)
[36, 21, 12, 9, 5]
>>> Def cmp_ignore_case (s1, s2): # compare two strings by case-insensitive
U1 = s1.upper ()
U2 = s2.upper ()
If u1 <u2:
Return-1
If u1> u2:
Return 1
Return 0
>>> Sorted (['bob', 'about', 'zoo', 'credentials'], cmp_ignore_case)
['About', 'bob', 'credentials', 'zoo']
Return Function
Def calc_sum (* args): # sum of variable parameters
Ax = 0
For n in args:
Ax = ax + n
Return ax
You do not need to sum immediately. Instead, you need to calculate the sum based on your needs in the subsequent code.
Def lazy_sum (* args ):
Def sum (): # defines the sum function.
Ax = 0
For n in args:
Ax = ax + n # reference the parameters and local variables of the external function lazy_sum
Return ax # This program structure is called a closure.
Return sum
>>> F = lazy_sum (1, 3, 5, 7, 9)
>>> F
<Function sum at 0x10452f668>
>>> F ()
25
>>> F1 = lazy_sum (1, 3, 5, 7, 9)
>>> F2 = lazy_sum (1, 3, 5, 7, 9)
>>> F1 = f2 # A new function is returned each time a call is made, and the result is independent of each other.
False
Anonymous Functions
>>> Map (lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
[1, 4, 9, 16, 25, 36, 49, 64, 81]
The anonymous function lambda x: x * x is actually:
Def f (x ):
Return x * x
>>> F = lambda x: x * x # assign an anonymous function to a variable and use the variable to call the function.
>>> F
<Function <lambda> at0x10453d7d0>
>>> F (5)
25
Decorator
Decorator is a high-level function that returns a function. Therefore, we need to define a decorator that can print logs, which can be defined as follows:
Def log (func): # decorator
Def wrapper (* args, ** kw ):
Print 'call % s (): '% func. _ name __
Return func (* args, ** kw)
Return wrapper
@ Log # Place the decorator in the definition of the Function
Def now ():
Print '2017-12-25'
>>> Now ()
Call now (): # print a line of log before running the now () function
Def log (text): # custom log text
Def decorator (func ):
Def wrapper (* args, ** kw ):
Print '% s ():' % (text, func. _ name __)
Return func (* args, ** kw)
Return wrapper
Return decorator
@ Log ('execute ') #3-layer nested decorator usage
Def now ():
Print '2017-12-25'
Partial functionPartial function
>>> Int ('20140901', base = 8) # input the base parameter to perform the N-base conversion.
5349
Def int2 (x, base = 2): # defines the int2 () function. By default, base = 2 is passed in.
Return int (x, base)
>>> Int2 ('20140901 ')
64
Functools. partial is used to create a partial function. You do not need to define int2 () by yourself. You can use the following code to create a new function int2:
>>> Import functools
>>> Int2 = functools. partial (int, base = 2)
>>> Int2 ('20140901 ')
64
Functools. partial is used to fix some parameters of a function (that is, to set the default value) and return a new function. It is easier to call this function.
Seeking attention and Diffusion