代码之家  ›  专栏  ›  技术社区  ›  Evan Aad

python中是否有创建递归列表的库函数?

  •  0
  • Evan Aad  · 技术社区  · 2 年前

    python中是否有一个库函数可以在以下意义上创建递归列表: recursive_list(f, x0, n) = [x0, f(x0), f(f(x0)), f(f(f(x0))), ...] 具有 n 返回列表中的元素?

    3 回复  |  直到 2 年前
        1
  •  3
  •   juanpa.arrivillaga    2 年前

    你可以使用 itertools.accumulate ,其工作原理类似于reduce,但会为您提供所有中间值

    def repeated_application(f_unary, x0, n):
        def f_binary(acc, _):
            return f_unary(acc)
        return itertools.accumulate(range(n), f_binary, initial=x0)
    

    你只需要把一元函数变成二元函数。

    注意,这会返回一个迭代器(更通用的方式)。

    此外,方式 n 应该工作的是未指定的,您可以根据自己的需求进行处理

    我还想指出,使用基本语言结构的直接方式是完全可以接受的;

    def recursive_application(f, x0, n):
        acc = x0
        result = [acc]
        for _ in range(n):
            acc = f(acc)
            result.append(acc)
        return result
    

    或者作为发电机,它非常干净:

    def repeated_application(f, x0, n):
        acc = x0
        yield acc
        for _ in range(n):
            acc = f(acc)
            yield acc
    
        2
  •  2
  •   trincot    2 年前

    标准库中没有这样的函数,但编写一个函数不需要太多代码:

    def recursive_list(f, x, n):
        return [x] + [x := f(x) for i in range(n-1)]
    
        3
  •  -1
  •   user2314737    2 年前

    如建议 here 使用 repeat 和 reduce :

    from itertools import repeat
    from functools import reduce
    def repeated(func, n):
        def apply(x, f):
            return f(x)
        def ret(x):
            return reduce(apply, repeat(func, n), x)
        return ret
    
    recursive_list = [repeated(f, i) for i in range(5)]
    

    递归列表中的元素是函数。

    例如

    def f(x):
        return x*x
    recursive_list[3](2)
    # 256