You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现返回重复执行指定函数n次的Python高阶函数?

解决new_repeat_function的闭包陷阱问题

我来帮你搞定这个问题!你的核心思路完全没问题,但代码栽在了Python闭包的延迟绑定特性上——这是个很常见的新手陷阱,咱们一步步拆解:

为什么你的原代码会出错?

你写的循环里,每次创建的lambda x : function(result(x))并没有立刻捕获当前的result值,而是在调用lambda的时候才去查找result变量的当前状态。等循环结束后,所有lambda里的result都指向了循环最后一次赋值的那个lambda,这就导致调用new_function(10)时,会陷入异常的调用逻辑,自然得不到正确结果。

几种可行的修复方案

方案1:用默认参数捕获当前的result值

默认参数是在lambda定义时就求值的,所以每次循环都能把当前的result快照保存下来:

def new_repeat_function(n, function):
    result = lambda x: function(x)
    for i in range(n-1):
        # 通过默认参数current_result捕获当前循环的result
        result = lambda x, current_result=result: function(current_result(x))
    return result

def times_three(x):
    return x * 3

new_function = new_repeat_function(3, times_three)
print(new_function(10))  # 输出270,符合预期

方案2:用嵌套函数封装循环(最直观,和原逻辑一致)

这个方法和你写的repeat_function逻辑几乎一样,只是把循环逻辑封装到返回的函数里,完全避开闭包陷阱:

def new_repeat_function(n, function):
    def output_function(x):
        current_value = x
        for _ in range(n):
            current_value = function(current_value)
        return current_value
    return output_function

# 测试
new_function = new_repeat_function(3, times_three)
print(new_function(10))  # 输出270

这种写法可读性最高,也最容易维护,推荐优先使用。

方案3:函数式风格——用reduce组合函数

如果你喜欢函数式编程,可以用functools.reduce把函数重复组合n次:

from functools import reduce

def new_repeat_function(n, function):
    # 定义函数组合逻辑:f(g(x))
    def compose(f, g):
        return lambda x: f(g(x))
    # 把function重复组合n次,初始值是恒等函数lambda x:x
    return reduce(compose, [function]*n, lambda x: x)

# 测试
new_function = new_repeat_function(3, times_three)
print(new_function(10))  # 输出270

验证结果

不管用哪种方案,new_function都等价于lambda x : times_three(times_three(times_three(x))),调用new_function(10)都会返回270,和你期望的结果一致。

内容的提问来源于stack exchange,提问作者Bharadwaj Akarapu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:19:26