例如: NestList(f,x,3) ----> [x, f(x), f(f(x)), f(f(f(x)))]
3 回答
            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))
或者,如果您希望将结果作为列表,您可以在循环中追加:
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)
于 2012-09-15T07:07:10.350   回答
    
    
            1        
        
		
def nest_list(f, x, i):
        if i == 0:
            return [x]
        return [x] + nest_list(f, f(x), i-1)
def nest_list(f, x, n):
    return [reduce(lambda x,y: f(x), range(i), x) for i in range(n+1)]
I found another way did it!
于 2012-09-15T08:54:09.547   回答
    
    
            1        
        
		
使用functional模块。它有一个名为 的函数scanl,它产生一个归约的每个阶段。然后,您可以减少f.
于 2012-09-16T19:22:24.320   回答