python advanced a (functional programming) [2-7 python anonymous function]

anonymous function in python

Higher-order functions can receive functions as parameters, sometimes, we do not need to explicitly define the function directly into the anonymous function more convenient.

In Python, to an anonymous function it provides limited support. Or to the map () function, for example, calculating f (x) = X , the addition to defining the outer a function f (x), and also directly into the anonymous function :

. 1 >>> Map ( the lambda X: X * X, [. 1, 2,. 3,. 4,. 5,. 6,. 7,. 8,. 9]) # the lambda is a function defined by X, x * x is the direct incoming function 
2 [1, 4, 9, 16, 25, 36, 49, 64, 81]

As it can be seen by comparing the anonymous function lambda x: x * x fact:

1 def f(x):
2     return x * x

Keyword lambda represents the anonymous function , before the colon  x denotes a function parameter .

Anonymous function has a limit, that is only one expression, do not write return, the return value is the result of the expression .

The use of anonymous functions, you can not define the function name directly create a function object, many times you can simplify the code:

task

By using anonymous functions to simplify the following code:

def is_not_empty(s):
    return s and len(s.strip()) > 0
filter(is_not_empty, ['test', None, '', 'str', '  ', 'END'])
1 print filter(lambda s: s and len(s.strip())>0, ['test', None, '', 'str', '  ', 'END'])

 

Guess you like

Origin www.cnblogs.com/ucasljq/p/11622007.html