# 为什么这两段python lambda出现不同的结果

``````[i(4) for i in [(lambda y: print('y=', y, '; x=', x, ' ; n + x = ', y + x)) for x in range(10)]]
``````

``````y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
``````

``````import functools

[f(4) for f in [functools.partial(lambda x, y: print('y=', y, '; x=', x, ' ; y + x = ', y + x), y) for y in range(10)]]

``````

``````y= 4 ; x= 0  ; y + x =  4
y= 4 ; x= 1  ; y + x =  5
y= 4 ; x= 2  ; y + x =  6
y= 4 ; x= 3  ; y + x =  7
y= 4 ; x= 4  ; y + x =  8
y= 4 ; x= 5  ; y + x =  9
y= 4 ; x= 6  ; y + x =  10
y= 4 ; x= 7  ; y + x =  11
y= 4 ; x= 8  ; y + x =  12
y= 4 ; x= 9  ; y + x =  13

``````

2 个回答

### 第一段 code

``[i(4) for i in [(lambda y: print('y=', y, '; x=', x, ' ; n + x = ', y + x)) for x in range(10)]]``

``funclist1 = [(lambda y: print('y=', y, '; x=', x, ' ; n + x = ', y + x)) for x in range(10)]``

``````def produce_functions():
funclist = []
for x in range(10):
def ld(y):
print('y=', y, '; x=', x, ' ; n + x = ', y + x)
funclist.append(ld)
return funclist

funclist2 = produce_functions()``````

``````>>> funclist1[0](4)
y= 4 ; x= 9  ; n + x =  13

>>> funclist2[0](4)
y= 4 ; x= 9  ; n + x =  13``````

``````>>> funclist1[0].__code__.co_freevars
('x',)
>>> funclist2[0].__code__.co_freevars
('x',)``````

``````>>> funclist2[0].__closure__
(<cell at 0x7f6e8ba22df8: int object at 0x9a34e0>,)

>>> funclist2[0].__closure__[0]
<cell at 0x7f6e8ba22df8: int object at 0x9a34e0>

>>> funclist2[0].__closure__[0].cell_contents
9``````

``````y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
y= 4 ; x= 9  ; n + x =  13
...``````

### 第二段 code

``````import functools

[functools.partial(lambda x, y: print('y=', y, '; x=', x, ' ; y + x = ', y + x), y) for y in range(10)]``````

`partial(func, a)` 會凍結 `func` 的第一個引數(會綁定 a 值)

### 結論

• `partial` 會直接凍結引數, 使變數代入定值

• 一般的 function 會直接參考到 free variable 而不是代入定值