本文介绍了奇怪的行为:列表理解中的 Lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 2.6 中:

In python 2.6:

[x() for x in [lambda: m for m in [1,2,3]]]

结果:

[3, 3, 3]

我希望输出为 [1, 2, 3].即使使用非列表理解方法,我也会遇到完全相同的问题.即使在我将 m 复制到不同的变量之后.

I would expect the output to be [1, 2, 3]. I get the exact same problem even with a non list comprehension approach. And even after I copy m into a different variable.

我错过了什么?

推荐答案

为了让 lambdas 记住 m 的值,你可以使用一个带有默认值的参数:

To make the lambdas remember the value of m, you could use an argument with a default value:

[x() for x in [lambda m=m: m for m in [1,2,3]]]
# [1, 2, 3]

这是有效的,因为默认值在定义时设置一次.现在,每个 lambda 都使用自己的默认值 m,而不是在 lambda 执行时在外部作用域中查找 m 的值.

This works because default values are set once, at definition time. Each lambda now uses its own default value of m instead of looking for m's value in an outer scope at lambda execution time.

这篇关于奇怪的行为:列表理解中的 Lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:45