gpt4 book ai didi

Python函数式迭代算法?

转载 作者:行者123 更新时间:2023-12-04 18:11:03 25 4
gpt4 key购买 nike

在 Haskell 中有一个简单的列表函数可用

iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)
在python中可以实现如下:
def iterate(f, init):
while True:
yield init
init = f(init)
我有点惊讶,像这样的基本东西不是 functools/itertools 模块的一部分。是否可以使用这些库中提供的工具以功能样式(即没有循环)简单地构建它? (主要是打代码,尝试学习 Python 中的函数式风格。)

最佳答案

您可以使用itertools 中的一些功能来完成。 :

from itertools import accumulate, repeat

def iterate(func, initial):
return accumulate(repeat(None), func=lambda tot, _: func(tot), initial=initial)
虽然它显然不是很干净。 Itertools 缺少一些用于构造流的基本函数,例如 unfoldr .大部分 itertools函数可以定义为 unfoldr ,碰巧,但是函数式编程在 Python 中有点不舒服,所以这可能没有太大的好处。

关于Python函数式迭代算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72059380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com