Execute functions in a list as a chain
In Python I defined these functions:
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
I want to execute these functions in a chain like this:
foo_1(foo_2(foo_3(foo_4(foo_5(1)))))
I'd like to specify these functions as a list, executing those functions in a chain with a precise sequence. This is what I've tried:
lf = [Null,foo_1,foo_2,foo_3,foo_4,foo_5] # Null is for +1 开发者_JAVA百科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)))
You can use reduce for this:
reduce(lambda x, y: y(x), list_of_functions, initial_value)
Like so:
reduce(lambda x, y: y(x), reversed([foo_1, foo_2, foo_3, ...]), 1)
Note that If you want to apply the functions in the order of foo_1(foo_2(etc...))
, you have to make sure that foo_1
is the last element of the list of functions. Therefore I use reversed
in the latter example.
No need for "Null" in "lf".
def execu(lst, seq, raw_para):
para = raw_para
for i in reversed(seq):
para = lst[i](para)
return para
def execu(lst, seq, raw_para):
return reduce(lambda x, y: y(x), reversed(operator.itemgetter(*seq)(lst)), raw_para)
精彩评论