使用itertools进行递归函数应用程序 [英] Using itertools for recursive function application

查看:137
本文介绍了使用itertools进行递归函数应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个Python函数 iterate(f,x)来创建一个返回值x,f(x),f(f(x)),f (f(f(x)))等(例如, Clojure的迭代 )。首先,我想知道:这是否已经存在于标准库中的某个地方,我只是错过了它?

I need a Python function iterate(f, x) that creates an iterator returning the values x, f(x), f(f(x)), f(f(f(x))), etc (like, e.g., Clojure's iterate). First of all, I was wondering: Does this already exist somewhere in the standard library and I'm only missing it? Of course it's easy enough to implement with a generator:

def iterate(f, x):
    while True:
        yield x
        x = f(x)

只是出于好奇:Is在Python中有更多功能的方法来实现这一点,例如与一些itertools或functools魔术?

Just out of curiosity: Is there a more functional way to do this in Python, e.g. with some itertools or functools magic?

在Python 3.3中,这将工作

In Python 3.3 this would work

def iterate(f, x):
    return accumulate(repeat(x), lambda acc, _ : f(acc))

但看起来对我来说是一种虐待。我能更好地做到这一点吗?

but looks like an abuse to me. Can I do this more nicely?

推荐答案

在itertools中似乎没有什么能够做到你想要的,但itertools是一个深藏宝箱,所以我可能错过了什么。

There doesn't seem to be something in itertools that does what you want, but itertools is a deep treasure chest, so I could have missed something.

您的生成器代码看起来很棒。我不知道你为什么要用积累来写它,除非你打了一场荒谬的高尔夫比赛,或者你想让Haskell势不可挡。编写你的函数,使其可读,可理解和可维护。不需要太聪明。

Your generator code looks great. I don't know why you'd write it with accumulate unless you were playing an absurd game of code golf, or you were trying to impress Haskell snobs. Write your function so that it is readable, understandable, and maintainable. No need to be overly clever.

这篇关于使用itertools进行递归函数应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆