简体   繁体   English

嵌套 lambda 的 Python 列表仅执行 lambda 列表的最后一个元素

[英]Python list of nested lambdas executes last element of lambda list only

The following code snippet demonstrates that a list of nested lambdas evaluates to the last element of the original list of lambdas only.以下代码片段演示了嵌套 lambda 列表仅计算原始 lambda 列表的最后一个元素。

eqs_test = [
    (lambda x: f"0"),
    (lambda x: f"1"),
    (lambda x: f"2"),
    (lambda x: f"3"),
]

# unexpected output
print([a(1) for a in [
    lambda x: f"{e1(0)}-{e2(0)}" for e1, e2 in zip(eqs_test[1:], eqs_test[:-1])
]])

# expected output (no outer lambda used here for testing)
print([a for a in [
    f"{e1(0)}-{e2(0)}" for e1, e2 in zip(eqs_test[1:], eqs_test[:-1])
]])

The output is:输出是:

['3-2', '3-2', '3-2']
['1-0', '2-1', '3-2']

I would expect the second output in both cases but somehow the lambda is not stored properly ( 3-2 is only the last generated lambda).我希望在这两种情况下都有第二个输出,但不知何故 lambda 没有正确存储( 3-2只是最后生成的 lambda)。 What is happening here and how can I store the outer lambda in such a way that it runs the correct nested lambda?这里发生了什么,我如何以运行正确嵌套 lambda 的方式存储外部 lambda?

To make the first example work, store the variables as lambda parameters.要使第一个示例工作,请将变量存储为 lambda 参数。 Otherwise, the lambda will print last values of e1 and e2 always:否则,lambda 将始终打印e1e2最后一个值:

eqs_test = [
    (lambda x: f"0"),
    (lambda x: f"1"),
    (lambda x: f"2"),
    (lambda x: f"3"),
]

# unexpected output
print([a(1) for a in [
    lambda x, e1=e1, e2=e2: f"{e1(0)}-{e2(0)}" for e1, e2 in zip(eqs_test[1:], eqs_test[:-1])
]])

Prints:印刷:

['1-0', '2-1', '3-2']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM