[英]Better way to call a chain of functions in python?
I have a chain of operations which needs to occur one after the other and each depends on the previous function's output. 我有一系列操作需要一个接一个地发生,每个操作都依赖于前一个函数的输出。
Like this: 像这样:
out1 = function1(initial_input)
out2 = function2(out1)
out3 = function3(out2)
out4 = function4(out3)
and so on about 10 times. 等约10次。 It looks a little ugly in the code.
它在代码中看起来有点难看。
What is the best way to write it? 写它的最佳方法是什么? Is there someway to handle it using some functional programming magic?
有没有办法使用一些函数编程魔术处理它? Is there a better way to call and execute this function chain?
有没有更好的方法来调用和执行这个功能链?
Use a loop: 使用循环:
out = initial_input
for func in [function1, function2, function3, function4]:
out = func(out)
You can use functools.reduce: 你可以使用functools.reduce:
out = functools.reduce(lambda x, y : y(x), [f1, f2, f3, f4], initial_value)
Quoting functools.reduce documentation: 引用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).
例如,reduce(lambda x,y:x + y,[1,2,3,4,5])计算(((((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.
如果存在initial,则将其放在计算中序列的项之前,并在序列为空时用作默认值。
Here, we use the fact that functions can be treated as any variable in Python, and an anonymous functions which simply does "apply x to function y". 在这里,我们使用的事实是函数可以被视为Python中的任何变量,而匿名函数只是“将x应用于函数y”。
This "reduce" operation is part of a very general pattern which have been applied successfully to parallelize tasks (see http://en.wikipedia.org/wiki/MapReduce ). 这种“减少”操作是一种非常通用的模式的一部分,它已成功应用于并行化任务(参见http://en.wikipedia.org/wiki/MapReduce )。
To propagate functional programming a bit: 传播函数式编程:
In [1]: compose = lambda f, g: lambda arg: f(g(arg))
In [2]: from functools import reduce
In [3]: funcs = [lambda x:x+1, lambda x:x*2]
In [4]: f = reduce(compose, funcs)
In [5]: f(1)
Out[5]: 3
In [6]: f(3)
Out[6]: 7
You can pass the return values directly to the next function: 您可以将返回值直接传递给下一个函数:
out4 = function4(function3(function2(function1(initial_input))))
But this isn't necessarily better, and is perhaps less readable. 但这不一定更好,也许可读性较差。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.