Python中的多变量lambda函数可根据接收到的输入变量的数量进行缩放 [英] Multivariate lambda function in Python that scales with number of input variables received

查看:81
本文介绍了Python中的多变量lambda函数可根据接收到的输入变量的数量进行缩放的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下玩具函数通常带有两个输入变量:

The following toy function ordinarily takes two input variables:

f = lambda u1, u2 : (u1*u2)*(u1**2+u2**2)

但可以扩展到双变量以外的情况,以达到更高的维度:

but can scale beyond the bivariate case to higher dimensions:

if dim == 2:
    f = lambda u1, u2 : (u1*u2)*(u1**2+u2**2)
if dim == 3:
    f = lambda u1, u2, u3 : (u1*u2*u3)*(u1**2+u2**2+u3**2)
if dim == 4:
    f = lambda u1, u2, u3, u4 : (u1*u2*u3*u4)*(u1**2+u2**2+u3**2+u4**2)

如何编写lambda函数,以便可以根据发送给它的输入数量在调用lambda u1, u2, u3, u4, ... 中扩展自身以及函数主体本身,类似于如何将定义的函数声明为def f(*args)其中*args是任意数量的输入参数吗?

How can the lambda function be written so that it can expand itself in the call lambda u1, u2, u3, u4, ... as well as the function body itself, based on number of inputs sent to it, similar to how a defined function can be declared as def f(*args) where *args is an arbitrary number of input arguments?

推荐答案

lambda语法支持与 语法,包括可变位置和关键字参数.

The lambda syntax supports the same parameter list syntax as the def syntax, including variadic positional and keyword argument.

f = lambda *us: math.prod(us) * sum(u**2 for u in us)

如果*us乘以1或加到0时不是不变的,则可以通过*和+运算. python.org/3/library/functools.html#functools.reduce"rel =" nofollow noreferrer> reduce :

If the *us are not invariant when multiplied by 1 or added to 0, the * and + operations can be applied across elements via reduce:

from functools import reduce
import operator

f = lambda *us: reduce(operator.mul, us) * reduce(operator.add, (u**2 for u in us))

这篇关于Python中的多变量lambda函数可根据接收到的输入变量的数量进行缩放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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