Mar*_*ers 6

你可以把它写成一个发电机:

def nestList(f,x,c):
    for i in range(c):
        yield x
        x = f(x)
    yield x

import math
print list(nestList(math.cos, 1.0, 10))
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望将结果作为列表,则可以在循环中追加:

def nestList(f,x,c):
    result = [x]
    for i in range(c):
        x = f(x)
        result.append(x)
    return result

import math
print nestList(math.cos, 1.0, 10)
Run Code Online (Sandbox Code Playgroud)

  • @chyanog:不,不难.但为什么你想要一个递归版本?对于第三个参数的大值,它的效率会降低并溢出堆栈. (2认同)