首页 > 解决方案 > 边缘化多元 lambda 函数

问题描述

我有一个函数 f 取决于可变数量的参数。例如,假设它取决于 4 个参数。

f = lambda x_1,x_2,x_3,x_4: *function’s body*

给定一个任意大小为 3 的整数元组 t,我想通过每次省略一个参数来评估该元组上的函数 f:

f_1 = lambda x_1 : f(x_1,*t)
f_2 = lambda x_2 : f(t[0],x_2, *t[1:])
f_3 = lambda x_3 : f(t[0],t[1],x_3, *t[2:])
f_4 = lambda x_4 : f(*t,x_4)

对于任意数量的参数,是否有一种通用方法来计算这些函数?我想遍历参数,但是绑定值似乎很麻烦,尤其是当参数的数量是可变的时。

这将帮助我计算函数的边缘。我希望我的问题很清楚!

标签: pythoncumulative-sum

解决方案


make_subfunctions获取一个函数和一个固定参数列表,并返回一个接受一个参数的子函数列表。

  1. 结果函数应该调用原始函数f(*fixed_args[:i], the_only_argument, *fixed_args[i:])。我们需要一个wrapper()或一个代理来完成这项工作。
  2. fixed_args[:i]fixed_args[i:]对于每个包装器都是固定的,我们可以使用它来functools.partial预先填充这两个参数,并让调用者填充其余的动态参数。因此,包装签名是(head, tail, x).
  3. startlast参数指定插入到固定参数的动态参数的(包括)索引。

输出:

('a', 0, 'b', 'c', 'd')
('a', 'b', 1, 'c', 'd')
('a', 'b', 'c', 2, 'd')
('a', 'b', 'c', 'd', 3)
from functools import partial


def make_subfunctions(f, fixed_args, start=0, last=None):
    fixed_args = tuple(fixed_args)

    if last is None:
        last = len(fixed_args)

    def wrapper(head, tail, x):
        return f(*head, x, *tail)

    fns = [partial(wrapper, fixed_args[:i], fixed_args[i:]) for i in range(start, last + 1)]

    return fns


def hello_world(*args):
    print(args)


def main():
    fixed_args = ['a', 'b', 'c', 'd']
    fns = make_subfunctions(hello_world, fixed_args, start=1)

    for i in range(len(fns)):
        fns[i](i)


if __name__ == '__main__':
    main()



推荐阅读