以下 Python 程序打印 13 而不是 7。
increment_by_i = [lambda x: x+i for i in range(10)]
print(increment_by_i[3](4))
我不明白以下给出的解释:
This is because the functions created in the loop have the same scope. They use the same variable name, and hence, consequently, all refer to the same variable i, which is 9 at the end of the loop.
- 列表推导式如何在列表中创建相应的函数?特别是,它与下面生成
increment_by_i
的代码有何不同?
increment_by_i_modify=[]
for i in range(10):
increment_by_i_modify.append(lambda x: x+i)
print(increment_by_i_modify[3](4))
- 我不明白“它们使用相同的变量名称,因此全部引用相同的变量
i
,即循环末尾的 9”这句话。 如果我写
test=[i for i in range(10)]
test[3]
是 3 而不是 9。
最佳答案
与初始列表理解等效的代码具有相同的行为/输出
如果您进行测试,您将看到 print(increment_by_i_modify[3](4))
具有相同的输出,13
您的函数不保留 i
的值,而是保留对 i
的引用,也许以下代码会有所帮助:
def get_functions():
increment = 0
variables = {'i': increment}
my_functions = []
def create_function():
def f(x):
return x + variables['i']
return f
while increment < 10:
my_functions.append(create_function())
variables['i'] = increment
increment += 1
return my_functions
increment_by_i = get_functions()
print(increment_by_i_modify[3](4))
输出:
13
关于python - 使用列表理解生成的函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944121/