问题描述
我在列表中有很多功能:
I have a bunch of functions in a list:
funcs = [f1, f2, f3, f4, f5]
和所有函数都返回一个参数,例如.
and all of the functions take in return a single argument, eg.
f1 = lambda x: x*2
我想将所有这些功能映射在一起
I'd like to map all these functions together
result = lambda x: f5(f4(f3(f2(f1(x)))))
或遍历funcs
def dispatch(x):
for f in funcs:
x = f(x)
return x
dispatch
可以正常工作,但是我想不出一种使用iterools
的干净方法.是否有可能?这个顺序函数映射习惯用法有名字吗?
dispatch
works fine, but I couldn't figure out a clean way to do this using iterools
. Is it possible? Does this sequential function mapping idiom have a name?
推荐答案
在这里使用itertools
没有意义;您正在产生一个输出,并且无法将其应用于无限迭代.您必须在输入中具有 finite 个可迭代的函数,此函数才能完全起作用.
There is no point in using itertools
here; you are producing one output, and you could not apply this to an infinite iterable. You have to have a finite number of functions in the input iterable for this to work at all.
使用 reduce()
函数:
from functools import reduce
x = reduce(lambda res, func: func(res), funcs, x)
functools.reduce()
导入可帮助上述工作Python 2和3.
The functools.reduce()
import helps the above work in both Python 2 and 3.
reduce()
和map()
,filter()
以及(c3)是 函数式编程 .
reduce()
, together with map()
, filter()
and, yes, itertools
, is an often used tool in functional programming.
这篇关于python中的顺序函数映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!