在python中使用lambda表达式在循环内部生成函数 [英] Generating functions inside loop with lambda expression in python

查看:790
本文介绍了在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)]

为什么列表ab不能以保存方式运行?

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表达式在循环内部生成函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆