1. What is lambda?
Func=lambda X:x+1print (func (1)) #2print (func (2)) #3 # above Lambda equals the following function def func (x): return (x+1)
It can be thought that lambda, as an expression, defines an anonymous function, where code x is the entry parameter and x+1 is the function body. Here Lambda simplifies the writing of function definitions. Code is more concise, but the use of functions is more intuitive and easy to understand.
In Python, there are also several well-defined global functions that are easy to use, filter, map, reduce.
From functools import reduce foo = [2, 9, 8, A, 27]print (list (filter (lambda x:x% 3 = = 0, foo)) #[18, 9 , 2, 27]print (list (map (lambda x:x * +, foo))) #[14, x, I, Si, si, si, si, 64]print (Reduce (lambda x, y:x + y, foo)) #139
The role of the map in the example above is very simple and clear. But does Python have to use lambda to make this simple? In the object traversal process, in fact Python for. In.. The IF syntax is already strong and is more readable than lambda.
For example, the map above can be written as: print ([x * 2 + x in Foo]) is very concise and easy to understand.
The filter example can be written as: print ([x for X in foo if x% 3 = = 0]) is also easier to understand than Lambda's way.
A brief introduction to lambda in Python