K. *_* C 1 python function composition
在python中我定义了函数:
def foo_1(p): return p + 1
def foo_2(p): return p + 1
def foo_3(p): return p + 1
def foo_4(p): return p + 1
def foo_5(p): return p + 1
Run Code Online (Sandbox Code Playgroud)
我需要执行这些功能,因为链可能是这样的:
foo_1(foo_2(foo_3(foo_4(foo_5(1)))))
Run Code Online (Sandbox Code Playgroud)
我是否可以知道是否可以将函数推入列表然后将这些函数作为链执行,也许我可以给出执行序列?
lf = [Null,foo_1,foo_2,foo_3,foo_4,foo_5] # Null is for +1 issue here
def execu(lst, seq, raw_para):
# in some way
execu(lf,(1,2,3,4,5), 1) # = foo_1(foo_2(foo_3(foo_4(foo_5(1)))))
execu(lf,(1,2,3), 1) # = foo_1(foo_2(foo_3(1)))
execu(lf,(3,3,3), 1) # = foo_3(foo_3(foo_3(1)))
Run Code Online (Sandbox Code Playgroud)
谢谢!
RGS,
KC
您可以为此使用reduce:
reduce(lambda x, y: y(x), list_of_functions, initial_value)
Run Code Online (Sandbox Code Playgroud)
像这样:
reduce(lambda x, y: y(x), reversed([foo_1, foo_2, foo_3, ...]), 1)
Run Code Online (Sandbox Code Playgroud)
请注意,如果要按 的顺序应用函数,则foo_1(foo_2(etc...))必须确保foo_1是函数列表的最后一个元素。因此我reversed在后一个例子中使用。
"lf"中不需要"Null".
def execu(lst, seq, raw_para):
para = raw_para
for i in reversed(seq):
para = lst[i](para)
return para
Run Code Online (Sandbox Code Playgroud)
def execu(lst, seq, raw_para):
return reduce(lambda x, y: y(x), reversed(operator.itemgetter(*seq)(lst)), raw_para)
Run Code Online (Sandbox Code Playgroud)