我显然误解了lambda如何在这里工作:
def get_res_lambda():
res = []
for v in ['one', 'two', 'three']:
res.append(lambda: v)
return res
def get_res():
res = []
for v in ['one', 'two', 'three']:
res.append(v)
return res
print ">>> With list"
res = get_res()
print(res[0])
print(res[1])
print(res[2])
print ">>> With lambda"
res = get_res_lambda()
print(res[0]())
print(res[1]())
print(res[2]())
我明白了:
>>> With list
one
two
three
>>> With lambda
three
three
three
我在期待:
>>> With list
one
two
three
>>> With lambda
one
two
three
为什么lambda版本总是返回最后一个值?我做错了什么?
答案 0 :(得分:4)
lambda函数在执行lambda函数时返回v
的值。当达到print(res[0]())
等
到那时for v in ['one', 'two', 'three']
已经完全完成了循环,v
的最终值为'three'
。