Qun*_*zed 2 python function concatenation
我需要编写一个名为'concat' 的python 函数,它接受任意两个函数作为输入,并返回一个函数,该函数是两个输入函数的连接函数(即它接受f1 和f2,并返回f1?f2)。
我试过这个:
def concat(f1,f2):
return f1(f2)
Run Code Online (Sandbox Code Playgroud)
例如,如果 f1 和 f2 是:
def f1(x):
return x+2
def f2(x):
return x*2
Run Code Online (Sandbox Code Playgroud)
然后, concat(f1,f2) 应该返回: (x*2)+2
我希望能够像这样使用它:
a = concat(f1,f2)
a(5)
Run Code Online (Sandbox Code Playgroud)
但我收到一个错误:
类型错误:不支持 + 的操作数类型:'function' 和 'int'
我知道我可以这样定义函数:
def concat(f1,f2,x):
return f1(f2(x))
Run Code Online (Sandbox Code Playgroud)
但这不是我想要的;我希望能够创建 concat 函数的实例,然后可以用任何 x 调用它。
您需要返回一个新的“包装器”函数。一种选择是使用lambda
表达式:
def concat(f1, f2):
return lambda x: f1(f2(x))
Run Code Online (Sandbox Code Playgroud)
文档: https : //docs.python.org/3/tutorial/controlflow.html#lambda-expressions