Tag: Port uses code to simplify toolbar BSP LTE list and
In the process of learning Python, Lambda's syntax often appears, and now it's sorted out for later viewing.
1. What is lambda?
Here's an example:
1 func=lambda x:x+12 Print (func (1)) 3 #24 Print (func (2)) 5 #36 7 #以上lambda等同于以下函数8 def func (x): 9 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.
1 from functools import reduce 2 foo = [2,, 9,,, 8,, +] 3 4 print (list (filter (lambda x:x% 3 = = 0, Foo))) 5 #[18, 9,, 6 7 print (list (map (lambda x:x * 2 +, foo)) 8 #[14, 46, 28, 54, 44, 58, 26, 34, 9 Print (Reduce (lambda x, y:x + y, foo) one #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