在python中使用lambda表达式在循环内部生成函数

编程入门 行业动态 更新时间:2024-10-12 12:24:19
本文介绍了在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表达式在循环内部生成函数

本文发布于:2023-11-22 01:32:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615453.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   函数   python   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!