lambda函数和Python中的函数列表 [英] lambda functions and list of functions in Python
本文介绍了lambda函数和Python中的函数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一系列函数,例如:
I have an array of functions, for example:
>>> def f():
... print "f"
...
>>> def g():
... print "g"
...
>>> c=[f,g]
然后我尝试创建两个lambda函数:
Then i try to create two lambda functions:
>>> i=0
>>> x=lambda: c[i]()
>>> i+=1
>>> y=lambda: c[i]()
然后给他们打电话:
>>> x()
g
>>> y()
g
为什么lambda中的c [i]相同?
Why c[i] in lambda are the same?
推荐答案
这是因为lambda函数正在运行时获取全局变量i
的值:
That's because the lambda function is fetching the value of the global variable i
at runtime:
>>> i = 0
>>> x=lambda z = i : c[z]() #assign the current value of `i` to a local variable inside lambda
>>> i+=1
>>> y =lambda z = i : c[z]()
>>> x()
f
>>> y()
g
A必须阅读: (lambda)函数闭包捕获了什么?
这篇关于lambda函数和Python中的函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文