Is there a function that applies list of functions to a value?
fp2161 at gmail.com
fp2161 at gmail.com
Thu Aug 29 18:48:15 EDT 2013
On Wednesday, August 28, 2013 3:10:49 PM UTC+2, Jussi Piitulainen wrote:
> AdamKal writes:
>
>
>
> > Hi,
>
> >
>
> > From time to time I have to apply a series of functions to a value
>
> > in such a way:
>
> >
>
> > func4(func3(func2(func1(myval))))
>
> >
>
> > I was wondering if there is a function in standard library that
>
> > would take a list of functions and a initial value and do the above
>
> > like this:
>
> >
>
> > func_im_looking_for([func1, func2, func3, func4], myval)
>
> >
>
> > I looked in itertools but nothing seamed to do the job. This seams
>
> > like something vary obvious that was needed many times elsewhere so
>
> > maybe you could help me?
>
>
>
> If you can have things backwards, or have func_im_looking_for reverse
>
> things first, you can do it this way:
>
>
>
> from functools import reduce
>
>
>
> def funcall(arg, fun): return fun(arg)
>
>
>
> def func1(arg): return 'f1({})'.format(arg)
>
> def func2(arg): return 'f2({})'.format(arg)
>
> def func3(arg): return 'f3({})'.format(arg)
>
>
>
> # prints: f1(f2(f3(3.14)))
>
> print(reduce(funcall, (func3, func2, func1), 3.14))
I had never thought about the "f({0})".format(arg) trick, that is excellent, thank you!!!
More information about the Python-list
mailing list