Python中的闭包和循环 [英] Closures and Loops in Python

查看:111
本文介绍了Python中的闭包和循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Python中的词法闭包

假设我有以下代码



Suppose I have the following code

callbacks = []
for i in range(10):
  callbacks.append(lambda x: i)

callbacks 中的所有函数将返回 i 的最终值。如何创建在创建时返回当前值的回调

all functions in callbacks will return the final value of i. How can I create callbacks that return the current value for i at creation time?

推荐答案

for i in range(10):
  callbacks.append(lambda x = i : x)

这篇关于Python中的闭包和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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