如何在python中编写函数n次

Gar*_*eld 2 python python-3.x

我知道如何通过将两个函数作为输入并输出其组合函数来组合两个函数,但是如何返回组合函数f(f(... f(x)))呢?谢谢

def compose2(f, g):
    return lambda x: f(g(x))

def f1(x):
    return x * 2
def f2(x):
    return x + 1

f1_and_f2 = compose2(f1, f2)
f1_and_f2(1)
Run Code Online (Sandbox Code Playgroud)

Mad*_*ist 5

您可以在嵌套函数内部使用循环:

def compose(f, n):
    def fn(x):
        for _ in range(n):
            x = f(x)
        return x
    return fn
Run Code Online (Sandbox Code Playgroud)

fn将具有闭包,该闭包保留对fn调用的引用compose