Composing functions in python

前端 未结 12 1265
北荒
北荒 2020-11-27 03:56

I have an array of functions and I\'m trying to produce one function which consists of the composition of the elements in my array. My approach is:

def compo         


        
12条回答
  •  感动是毒
    2020-11-27 04:05

    You can also create an array of functions and use reduce:

    def f1(x): return x+1
    def f2(x): return x+2
    def f3(x): return x+3
    
    x = 5
    
    # Will print f3(f2(f1(x)))
    print reduce(lambda acc, x: x(acc), [f1, f2, f3], x)
    
    # As a function:
    def compose(*funcs):
        return lambda x: reduce(lambda acc, f: f(acc), funcs, x)
    
    f = compose(f1, f2, f3)
    

提交回复
热议问题