Objective:
A lambda function is also called an anonymous function, that is, the function does not have a specific name.
First, the basic
A lambda statement is actually built as a function object. There is a limit to the anonymous function, that is, there can be only one expression, without writing return, the return value is the result of that expression.
Lambda (a,b:a+b) #关键字lambda表示匿名函数, the colon is preceded by a parameter, can have multiple, separated by commas, and the return value to the right of the colon.
Lambda Benefits:
1, using Python to write some execution scripts, using lambda can eliminate the process of defining functions, so that the code is more streamlined.
2, for some of the abstract, will not be another place to reuse the function, sometimes to a function name is also a problem, using lambda does not need to consider the problem of naming.
3. Using lambda makes the code easier to understand at some point.
to give a simple example: Def f (x): return x**2 print f (4= lambda x:x**2print g ( 4)
Second, advanced-built-in functions
1. Map ()
Iterates through the sequence, operates on each element of the sequence, and finally gets a new sequence.
Li = [all] = [123= map (lambda A, b:a + B, Li, SL) print (list (new_list)) Results output as:>>>[, [+]
2. Reduce ()
Cumulative operation for all elements within a sequence
from = [one,three,four = reduce (lambda a,b:a+b,li) # The first parameter of reduce, The function must have two parameters # reduce the second parameter, to loop the third parameter of the sequence # reduce, the initial value of the print (result) output:>>>
3. Filter ()
Filter the elements in a sequence, and finally get a sequence that matches the criteria
Li = [one,one,and the other = filter (lambda a:a>, li) print (list (new_ List) #filter第一个参数为空, the original sequence output will be obtained:>>>[]
Above ~
Python-lambda usage