python tips: anonymous lambda function

lambda is used to create an anonymous function, the following two ways equivalent to the function definition.

1 f = lambda x: x + 2
2 
3 def f(x):
4     return x + 2 

Anonymous function immediately executed

(lambda x: print(x))(2)

Output

1 2

Anonymous function to achieve closure

 1 f = lambda x:lambda y: x & y
 2 
 3 x = 1 << 5
 4 t = f(x)
 5 print(t(0))
 6 print(t(32))
 7 
 8 # f的等价形式
 9 def f(x):
10     def s(y):
11         return x & y
12     return s

Output

1 0
2 32

 

Guess you like

Origin www.cnblogs.com/luoheng23/p/11005379.html