python - 边缘化多元 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)
对于任意数量的参数,是否有一种通用方法来计算这些函数?我想遍历参数,但是绑定值似乎很麻烦,尤其是当参数的数量是可变的时。
这将帮助我计算函数的边缘。我希望我的问题很清楚!
解决方案
make_subfunctions
获取一个函数和一个固定参数列表,并返回一个接受一个参数的子函数列表。
- 结果函数应该调用原始函数
f(*fixed_args[:i], the_only_argument, *fixed_args[i:])
。我们需要一个wrapper()
或一个代理来完成这项工作。 fixed_args[:i]
和fixed_args[i:]
对于每个包装器都是固定的,我们可以使用它来functools.partial
预先填充这两个参数,并让调用者填充其余的动态参数。因此,包装签名是(head, tail, x)
.start
和last
参数指定插入到固定参数的动态参数的(包括)索引。
输出:
('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()
推荐阅读
- powershell - 无法在 Powershell 中使用 Gmail SMTP 发送电子邮件。错误:smtpServer 需要安全连接或客户端未通过身份验证。怎么修?
- db2 - IBM DB2 ODBC 驱动程序为 ODBC API SQLGetInfo() 返回错误的值
- javascript - 如何在 reactjs 中使用单个 ListItem 映射路由?
- angular - Angular / Typescript以编程方式将图像(blob)复制到剪贴板
- azure-devops - 从构建中自动设置 Release.ReleaseDescription。(Azure devops 管道)
- react-native - Expo AsyncStorage 返回承诺问题
- django - 测试 Django Rest Framework:如何测试超链接关系?
- javascript - 传单在 GeoJSON 层中移动多边形的单点
- scala - 在大范围内迭代的内存有效方法
- reactjs - 如何解决 Redux React Typescript Higher Order Component (Hoc) 编译错误“props and props” is incompatible