如何使用列表理解生成不同的lambda函数的列表? [英] How to generate a list of different lambda functions with list comprehension?

查看:57
本文介绍了如何使用列表理解生成不同的lambda函数的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题摘自涉及Tkinter按钮的回调函数的原始应用程序.这是说明行为的一行.

This question is distilled from the original application involving callback functions for Tkinter buttons. This is one line that illustrates the behavior.

lambdas = [lambda: i for i in range(3)]

如果您随后尝试调用生成的lambda函数,请执行以下操作: lambdas[0]()lambdas[1]()lambdas[2]()都返回2.

if you then try invoking the lambda functions generated: lambdas[0](), lambdas[1]() and lambdas[2]() all return 2.

所需的行为是使lambdas[0]()返回0,lambdas[1]()返回1,lambdas[2])()返回2.

The desired behavior was to have lambdas[0]() return 0, lambdas[1]() return 1, lambdas[2])() return 2.

我看到index变量是通过引用解释的.问题是如何重新表述按价值对待.

I see that the index variable is interpreted by reference. The question is how to rephrase to have it treated by value.

推荐答案

您可以使用

You can use functools.partial to create specialized functions from a more general one by partial application, which reduces the parameter count by one:

from functools import partial
lambdas = [partial(lambda x: x, i) for i in range(3)]

在这里,lambda x: x是带有一个参数的常规身份函数,您可以创建三个特殊化功能,不带任何参数,并返回固定值.

Here, lambda x: x is the general identity function taking one argument, and you create three specializations of it, taking no arguments, and returning fixed values.

这篇关于如何使用列表理解生成不同的lambda函数的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆