Lambda expression
anonymous functions
The-LAMDBA function is a minimal function that quickly defines a single line, borrowed from Lisp, and can be used wherever a function is needed.
Example:
Function:
>>> def fun (x, y): ... return x*y >>> fun (23,2) Lambda
Lambda X,y:x*y
#lambda function, x first argument, y second argument, x*y operation type, and if the object returned by the function is used, an accepted variable is required >>> A=lambda x,y:x*y>>> A (2,3) 6
Advantage:
When you write some execution scripts using Python, lambda can eliminate the process of defining a function and make the code more streamlined.
For abstractions, functions that do not need to be reused, it is difficult to define names, and the use of lambda does not need to consider name naming;
Using lambda makes the code easier to understand;
Lambda Basics
In a lambda statement, the colon is preceded by a parameter, can be multiple, separated by commas, and the right side of the colon is the return value.
The lambda statement is actually built as a function object;;
>>> Lambda x,y:x*y<function <lambda> at 0x7f9bed0d3578>>>> A=lambda x,y:x*y>>> A<function <lambda> at 0x7f9bed0e58c0>>>> A (2,2) 4
Lambda Application Example:
Reduce is a successive operation of each item in the list, the accepted parameter is 2, and the last returned is a result
Product >>> L=range (1,6) >>> l[1, 2, 3, 4, 5]>>> def f (x, y): ... return x*y ... >>> reduce (f,l) #将函数f, for L sequence 120 conversion >>> F=lambda x,y:x*y>>> reduce (f,l) 120>>> reduce (lambda x,y:x*y,l) #l列表120 >>>
This article from "thinking More than technology" blog, declined reprint!
Python Basic Learning lambda