Composing functions in python

前端 未结 12 1232
北荒
北荒 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条回答
  •  萌比男神i
    2020-11-27 04:18

    One liner:

    compose = lambda *F: reduce(lambda f, g: lambda x: f(g(x)), F)
    

    Example usage:

    f1 = lambda x: x+3
    f2 = lambda x: x*2
    f3 = lambda x: x-1
    g = compose(f1, f2, f3)
    assert(g(7) == 15)
    

提交回复
热议问题