优雅地应用Python函数列表 [英] Apply a list of Python functions in order elegantly

查看:96
本文介绍了优雅地应用Python函数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入值val和要按以下顺序应用的功能列表:

I have an input value val and a list of functions to be applied in the order:

funcs = [f1, f2, f3, ..., fn]

如何优雅地申请而不是写作

How to apply elegantly and not writing

fn( ... (f3(f2(f1(val))) ... )

也不使用for循环:

tmp = val
for f in funcs:
    tmp = f(tmp)

感谢马丁(Martijn)出色的回答.我发现有一些阅读资料: https://mathieularose.com/function-composition-in-python/.

Thanks Martijn for the awesome answer. There's some reading I found: https://mathieularose.com/function-composition-in-python/ .

推荐答案

使用 reduce()功能:

# forward-compatible import
from functools import reduce

result = reduce(lambda res, f: f(res), funcs, val)

reduce()将第一个参数(可调用)应用于从第二个参数获取的每个元素,加上到目前为止的累加结果(如(result, element)).第三个参数是一个起始值(否则将使用funcs中的第一个元素).

reduce() applies the first argument, a callable, to each element taken from the second argument, plus the accumulated result so far (as (result, element)). The third argument is a starting value (the first element from funcs would be used otherwise).

在Python 3中,内置函数已移至 functools.reduce()位置;为了向前兼容,Python 2.6及更高版本中提供了相同的参考.

In Python 3, the built-in function was moved to the functools.reduce() location; for forward compatibility that same reference is available in Python 2.6 and up.

其他语言可以将其称为折叠.

Other languages may call this folding.

如果每个功能也需要中间结果,请使用 itertools.accumulate() (仅从Python 3.3起,用于带有函数参数的版本):

If you need intermediate results for each function too, use itertools.accumulate() (only from Python 3.3 onwards for a version that takes a function argument):

from itertools import accumulate, chain
running_results = accumulate(chain(val, funcs), lambda res, f: f(res))

这篇关于优雅地应用Python函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆