Explain the usage of lambda function of Python in detail
- 2021-11-10 10:21:35
- OfStack
lambda Function Usage
lambda is a very important definition. lambda is bound at "runtime", and "not" is bound at definition. The following column:
Original intention: Let X be added to the numbers 0 to 1 respectively. x+0, x+1, x+2, x+3
The actual operation results are:
0
0
0
0
The reason mentioned above is that it is bound at runtime. The for loop that was run first could not be caught.
func = [lambda x: x + n for n in range(4)] # x+n , n Is from 0 To 3 For Cycle ,x+0,x+1,x+3
for f in func:
print(f(0)) # Print func The number of the list 1 Data.
-----------------------
Modified code: Added n=n
func = [lambda x,n=n:x+n for n in range(4)]
for f in func:
print(f(0))
Run results:
0
1
2
3
This is what we want to achieve. n = n, which is captured at definition time.
Reason:
n is a free variable and can only be determined at execution time.
We can just make n a parameter, because parameters can be defined with variables bound.
-----------------------
The following example is strange:
h = 1
a = lambda k: h + k
h = 2
b = lambda k: h + k
print(a(3))
print(b(3))
Run results:
5
5
The h=1 we assigned was not used at all. Always do the calculation 3 +2.
h=1
h=2
Are all global variables, the last one will prevail.
-----------------------
After modification
h = 1
a = lambda k,h=h: h + k
h = 3
b = lambda k,h=h: h + k
print(a(10))
print(b(10))
Run results:
11
13
-----------------------
h = 1
h = 100
a = lambda k,h=h: h + k
h = 3
b = lambda k,h=h: h + k
print(a(10))
print(b(10))
Results:
110
13
In the last example above, we found that h=1 and h=100, and only 100 was selected to participate in the calculation. 100+10=110 because h=1 and h=100 are global, whichever is last. The python code runs from top to bottom.