Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

functional programming - Apply a list of Python functions in order elegantly

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))) ... )

and also not using for loop:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...