python--杂识--理解[lambda x: x*i for i in range(4)]

tech2026-09-21  1

1.

题目:

lst = [lambda x: x*i for i in range(4)] res = [m(2) for m in lst] print(res) """ 运行结果: [6, 6, 6, 6] Process finished with exit code 0 """

理解:题目中得代码相当于以下代码

fun_list = [] for i in range(4): def foo(x): return x*i fun_list.append(foo) for m in fun_list: print(m(2)) """ 运行结果: 6 6 6 6 Process finished with exit code 0 """

2. 补充

如何输出[0, 2, 4, 6]

# 修改后得代码 lst = [lambda x, j=i: x*j for i in range(4)] res = [m(2) for m in lst] print(res) """ 运行结果: [0, 2, 4, 6] Process finished with exit code 0 """

理解:

fun_list = [] for i in range(4): def foo(x, j=i): return x*j fun_list.append(foo) for m in fun_list: print(m(2)) """ 运行结果: 0 2 4 6 Process finished with exit code 0 """
最新回复(0)