python - 在 python 中调用函数链的更好方法?

标签 python

我有一系列操作需要一个接一个地发生,每个操作都取决于前一个函数的输出。

像这样:

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/

相关文章:

python - 太多值无法解包 for 循环计数列表中的值时出现错误

python - pyspark 中的大型数据帧生成

python - 在 python 中查找大型二维矩阵中的模式的有效方法(Scipy)

python - 我怎样才能在 NumPy 中做这个 python 列表理解?

python - ImageData 生成器中的 validation_split 返回 0 个图像

python - 动态更改并行线程数

python - matplotlib:通过鼠标事件获取 3D 图中的坐标

python - 操作系统错误 : [Error 1] Operation not permitted

python - 为什么当我创建一个新的 worker 时,以前的 celery worker 的任务仍然存在?

python - 收到 501 服务器错误 : Not Implemented error when trying to backup Firebase from a remote server