Composing functions in python

前端 未结 12 1259
北荒
北荒 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:07

    The easiest approach would be first to write a composition of 2 functions:

    def compose2(f, g):
        return lambda *a, **kw: f(g(*a, **kw))
    

    And then use reduce to compose more functions:

    def compose(*fs):
        return reduce(compose2, fs)
    

    Or you can use some library, which already contains compose function.

提交回复
热议问题