flist = [] for i in range(3): def func(x): return x * i flist.append(func) for f in flist: print(f(2)) 如何改写上述代码解决上一个问题的功能bug,正确运行结果(0,2,4)
时间: 2023-06-05 08:08:22 浏览: 74
可以使用 lambda 表达式代替 def 函数来解决问题,如下所示:
flist = []
for i in range(3):
flist.append(lambda x, i=i: x * i)
for f in flist:
print(f(2))
运行结果为:0 2 4
相关问题
flist=[] for i in range(3): def func(x): return x * i flist.append(func) for f in flist: print(f(2)) 如何改写上述代码解决上一个问题的功能bug,正确运行结果(0,2,4)
可以修改代码如下:
flist = []
for i in range(3):
def func(x, i=i):
return x * i
flist.append(func)
for f in flist:
print(f(2))
输出结果为:0 2 4。
在修改后的代码中,将变量i作为默认参数传递给了函数func,这样每个函数func的i值就被固定为了循环变量i的值,就可以避免上一个代码中所遇到的问题了。
flist.append(lambda x, i=i: x * i)这句代码什么意思
这段代码实现了一个 lambda 函数,将 x 乘以一个变量 i,然后将这个 lambda 函数添加到 flist 列表中。在添加时,使用了 i=i 的 trick,将循环中的变量 i 作为默认参数传递给 lambda 函数,以避免在循环中出现变量绑定问题。
阅读全文
相关推荐















