python 中的顺序函数映射

Sequential function mapping in python

我在列表中有一堆函数:

funcs = [f1, f2, f3, f4, f5]

并且所有函数都接受 return 单个参数,例如

f1 = lambda x: x*2

我想将所有这些功能映射在一起

result = lambda x: f5(f4(f3(f2(f1(x)))))

或者,遍历 funcs

def dispatch(x):
    for f in funcs:
        x = f(x)
    return x

dispatch 工作正常,但我无法找到使用 iterools 的干净方法。可能吗?这个顺序函数映射成语有名字吗?

这里使用itertools没有意义;您正在生成 one 输出,并且您无法将其应用于无限迭代。您必须在输入可迭代中具有 有限 个函数才能正常工作。

使用reduce() function:

from functools import reduce

x = reduce(lambda res, func: func(res), funcs, x)

functools.reduce() import 有助于上述 Python 2 和 3 的工作。

reduce(),连同map()filter(),是的,itertools,是functional programming.[=21=中常用的工具]

查看 Martijn 答案的另一种(效率较低,唉)方式是意识到您想要编写函数列表。

# function composition: compose(f,g)(x) = f(g(x))
def compose(f, g):
    return lambda x: f(g(x))

# Identity for function composition
# compose(f, identity)(x) = f(x)
identity = lambda x: x

# result(x) = f1(f2(...fn(x)...))
result = reduce(compose, funcs, identity)