如何用Python编写类似Mma的NestList函数

2024-09-19 21:04:11 发布

您现在位置:Python中文网/ 问答频道 /正文

例如: 嵌套列表(f,x,3)--->;[x,f(x),f(f(x)),f(f(f(x)))]

http://reference.wolfram.com/mathematica/ref/NestList.html


Tags: gtcomrefhttp列表htmlwolframreference
3条回答
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)]

我找到了另一种方法!在

你可以把它写成生成器:

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))

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

^{pr2}$

使用functional模块。它有一个名为scanl的函数,该函数产生还原的每个阶段。然后可以减少f的实例列表。在

相关问题 更多 >