lambda令人惊讶的结果

时间:2017-01-09 12:00:51

标签: python lambda

我显然误解了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版本总是返回最后一个值?我做错了什么?

1 个答案:

答案 0 :(得分:4)

lambda函数在执行lambda函数时返回v的值。当达到print(res[0]())

时,将执行lambda函数

到那时for v in ['one', 'two', 'three']已经完全完成了循环,v的最终值为'three'