我有一系列操作需要一个接一个地发生,每个操作都取决于前一个函数的输出。
像这样:
out1 = function1(initial_input)
out2 = function2(out1)
out3 = function3(out2)
out4 = function4(out3)
以此类推约10次。它在代码中看起来有点难看。
最好的写法是什么?有没有办法使用一些函数式编程魔法来处理它?有没有更好的方法来调用和执行这个函数链?
最佳答案
您可以使用 functools.reduce:
out = functools.reduce(lambda x, y : y(x), [f1, f2, f3, f4], initial_value)
引用 functools.reduce 文档:
Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
在这里,我们使用函数可以被视为 Python 中的任何变量这一事实,以及一个简单地“将 x 应用于函数 y”的匿名函数。
这个“减少”操作是一个非常通用的模式的一部分,该模式已成功应用于并行化任务(参见 http://en.wikipedia.org/wiki/MapReduce)。
关于python - 在 python 中调用函数链的更好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20454118/