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

如何用生成器重写带helper的Python pipeline函数?

用生成器重写Pipeline函数

我有一个pipeline函数,可接收任意数量的函数作为参数,返回一个仅含单个参数的helper函数,该函数会迭代调用传入的函数。原代码如下:

def pipeline(*funcs):
    def helper(arg):
        for func in funcs:
            result = func(arg)
            arg = result
        return result
    return helper

测试用例:

fun = pipeline(lambda x: x * 3, lambda x: x + 1, lambda x: x / 2)
print(fun(3)) # should print 5.0

我了解到生成器可保存之前的状态,想知道能否用生成器重写当前的pipeline函数,替代当前用变量保存每次func调用时arg的方式。


解决方案

当然可以用生成器实现这个逻辑,生成器的状态保存特性正好能替代手动维护arg变量的操作。下面是重写后的代码:

def pipeline(*funcs):
    def helper(arg):
        # 定义生成器,逐步应用每个函数并传递状态
        def processing_gen():
            current_val = arg
            for func in funcs:
                current_val = func(current_val)
                yield current_val
        
        # 迭代生成器,获取最终结果
        final_result = None
        for val in processing_gen():
            final_result = val
        return final_result
    return helper

验证测试

运行原测试用例,结果和预期一致:

fun = pipeline(lambda x: x * 3, lambda x: x + 1, lambda x: x / 2)
print(fun(3)) # 输出 5.0

逻辑说明

  • processing_gen生成器内部维护了current_val变量,每次迭代时应用下一个函数并更新状态,然后yield当前计算值。
  • helper函数通过迭代这个生成器,最终取最后一次yield的值作为结果,完成整个流水线的计算。
  • 生成器自动保存了每次计算后的状态,不需要手动在循环外维护变量,完美替代了原代码中更新arg的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:33:28