Use the reduce()
function:
# forward-compatible import
from functools import reduce
result = reduce(lambda res, f: f(res), funcs, val)
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).
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.
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))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…