本文介绍了在python中使用lambda表达式在循环内部生成函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我列出两个函数列表:
If I make two lists of functions:
def makeFun(i): return lambda: i a = [makeFun(i) for i in range(10)] b = [lambda: i for i in range(10)]为什么列表a和b不能以保存方式运行?
why do lists a and b not behave in the save way?
例如:
>>> a[2]() 2 >>> b[2]() 9推荐答案
从技术上讲,lambda表达式在全局范围内可见的i上 closed 关闭.在所有10个lambda中都引用了 same i.例如,
Technically, the lambda expression is closed over the i that's visible in the global scope, which is last set to 9. It's the same i being referred to in all 10 lambdas. For example,
i = 13 print b[3]()在makeFun函数中,lambda在调用该函数时定义的i上关闭.那是十个不同 i s.
In the makeFun function, the lambda closes on the i that's defined when the function is invoked. Those are ten different is.
更多推荐
在python中使用lambda表达式在循环内部生成函数
发布评论