Python·关于 [lambda x: x*i for i in range(4)] 理解

题目

lst = [lambda x: x*i for i in range(4)]
res = [m(2) for m in lst]
print res

这个问题涉及到了Python的闭包及延时绑定的知识(Python作用域)。

在Python核心编程里,闭包的定义如下:

如果在一个内部函数里,对外部作用域(但不是在全局作用域)的变量进行引用,那么内部函数就被认定是闭包。

总结为三点:

1、是一个内嵌函数

2、对外部函数变量引用

3、外部函数返回内嵌函数

简单的闭包例子:

def counter(start_at=0):
    count = [start_at]
    def incr():
        count[0] += 1
        return count[0]
    return incr

上面的那道题,可以写成这样:

def func():
    fun_list = []
    for 

猜你喜欢

转载自blog.csdn.net/qq_37865996/article/details/124311407