【问题标题】:apply sequence of functions to an object in python将函数序列应用于python中的对象
【发布时间】:2026-02-04 21:10:01
【问题描述】:

基于string 形式的一组指令,我必须在一个对象上一个接一个地应用某些指令(fxns)。这是一个更大系统的一部分。我已经到了这一点。我需要一种迭代方法,并在指令末尾返回对象的条件。我遇到了this reference,但在那里,函数被应用于一个恒定的初始数据以获取输出列表。然而,在我的情况下,对象随着迭代而变化。因此while 声明,但我还需要一个iterate 来应用我的ith 函数。

我也尝试创建一个递归函数(它在 for 语句中,感觉完全不对),基本条件是指令长度达到 0,(每个递归调用都执行一条指令,直到不再剩下,因此它的复杂性也在降低),它看起来是一个很好的递归候选者,如果有人感兴趣,我会很感激这种方式的解决方案。

instruction_dict = {'D': lambda x : x/2 , 'M': lambda x: x%2, 'P':lambda x: x*2 , 'S': lambda x : x-2, 'A': lambda x : x+2}
instruction_set = 'PPPPPDDSAM'

def mycomputation (num):
    count, intermediate = 0, num
    fun_args = [instruction_dict[i] for i in instruction_set]

    while count <= len(fun_args):
        intermediate, count = fun_args(intermediate), count +1 #list is not callable, actually need fun_args[i](intermediate)
    return intermediate

fun_args 是一个列表,一个列表是不可调用的,实际上需要类似 - fun_args[i](intermediate)

【问题讨论】:

  • @khelwood 道歉。应该是固定的。

标签: python python-3.x class scope


【解决方案1】:

我认为您对递归的想法非常接近:

 def mycomputation(num, instruction_set):
     return num if not instruction_set else mycomputation(instruction_dict[instruction_set[0]](num), instruction_set[1:])

但是为什么不解码函数外部的指令集并传入初始对象和转换列表呢?它可以变成单行:

my_comp = lambda ini, funs: ini if not funs else my_comp(funs[0](ini), funs[1:])

print(my_comp("Hello, World", [
    lambda x: f"<h1>{x}</h1>", 
    lambda x: f"<body>{x}</body>", 
    lambda x: f"<html>{x}</html>",
])) # -> <html><body><h1>Hello, World</h1></body></html>
print(my_comp(2, [lambda x: x**2, lambda x: x+5, lambda x: x+7])) # -> 16
print(my_comp(2, [])) # -> 2 (noop)

【讨论】:

    【解决方案2】:

    解决方法很简单:

    def mycomputation(num):
        for instruction in instruction_set:
            num = instruction_dict[instruction](num)
        return num
    

    【讨论】:

      【解决方案3】:

      如果你有一个函数列表,你可以一个一个地应用它们:

      for fun in fun_args:
          intermediate = fun(intermediate)
      

      【讨论】:

        最近更新 更多