---
title: "关于 python 中使用 lambda 表达式的问题"
author: "winzenghua"
date: "2005-11-17T23:50:00Z"
tags: []
slug: "python-lambda"
draft: false
lastmod: "2005-11-17T23:50:00Z"
id: 950216
url: "https://java4gis.iteye.com/blog/950216"
---

关于 python 中 lambda 表达式的一些问题

如果你定义如下一个python的lambda 函数：

------------------------------&lt;wbr&gt;&lt;/wbr&gt;--  
def doLambda(val):  
print "value 2:", val

commands = \[]  
for value in range(5):  
print "value 1:", value  
commands.append(lambda:doLambda(value))

for c in commands:  
c()  
\------------------------------ &lt;wbr&gt;&lt;/wbr&gt;----

当你调用的时候却发现：doLambda 的value 总是4 ，如下：

&gt;&gt;&gt;  
value 1: 0  
value 1: 1  
value 1: 2  
value 1: 3  
value 1: 4  
value 2: 4  
value 2: 4  
value 2: 4  
value 2: 4  
value 2: 4

正确的方式应该如下：

\-------------------------------

def wrapper(val):  
def inner():  
print "value 2:", val  
return inner

commands = \[]  
for value in range(5):  
print "value 1:", value  
commands.append(wrapper(value))

for c in commands:  
c()

\-------------------------------

&gt;&gt;&gt;  
value 1: 0  
value 1: 1  
value 1: 2  
value 1: 3  
value 1: 4  
value 2: 0  
value 2: 1  
value 2: 2  
value 2: 3  
value 2: 4

或者：

\-----------------------------------

\######  
&gt;&gt;&gt; commands = \[]  
&gt;&gt;&gt; def sayNumber(n):  
... print n  
...  
&gt;&gt;&gt; for i in range(5):  
... commands.append((lambda v: lambda: sayNumber(v))(i))  
...  
&gt;&gt;&gt;  
&gt;&gt;&gt; for c in commands:  
... c()  
...  
0  
1  
2  
3  
4  
\######

\-----------------------------------