2014-02-12 31 views
1

的家庭,我想產生一系列相似的這個簡單的例子lambda函數:生成的lambda函數

fns = [(lambda x: x == y) for y in range(10)] 

結果我從這個得到確實的10個功能列表。但是,所有10個似乎都必須是9,這是序列的最後一個值。例如

[fns[i](9) for i in range(10)] --> [True, True, True, True, True, True, True, True, True, True] 
fns[0](0) --> False 

爲什麼不工作,以及乾淨的解決方法是什麼?

我已經在Python 2.7和3.3中試過了。

+0

將lambda定義更改爲'(lambda x,y = y:x == y)' – thefourtheye

回答

1

因評論而編輯。

>>> fns = [(lambda x,y = y: x == y) for y in range(10)] 
>>> map(lambda x: x(1), fns) 
[False, True, False, False, False, False, False, False, False, False] 
+0

如果我有另一個for循環呢?再一次嵌套lambda? – thefourtheye

+0

不,一個lambda是你需要的所有閉包。包含在編輯中的示例。 – placeybordeaux

+0

我們根本沒有另一個lambda。檢查我的問題中的評論。 – thefourtheye