Skip to content Skip to sidebar Skip to footer

Applying A Series Of Functions To A List

I have a list that looks like this: lst = [1, 2, 3, 4, 5, 6] I have numerous functions each with arguments: mul = lambda lst, val: [i * val for i in lst] add = lambda lst, val1, v

Solution 1:

This does what you want:

mul = lambda lst, val: [i * val for i in lst]
add = lambda lst, val1, val2: [i + val1 + val2 for i in lst]

deffunctions(lst, *fns):
    for fn, args in fns:
        lst = fn(lst, *args)
    return lst

lst = [1, 2, 3, 4, 5, 6]
result = functions(lst, [mul, (10,)], [add, (10, 100)])
print result

produces:

[120, 130, 140, 150, 160, 170]

You might like to structure the functions differently:

mul = lambda i, val: i * val
add = lambda i, val1, val2: i + val1 + val2

deffunctions(lst, *fns):
    for fn, args in fns:
        lst = [fn(i, *args) for i in lst]
    return lst

And as others point out: numpy is designed to do all this and much much more.

Solution 2:

Use functools.partial, chained. E.g.,

from functools import partial

lst = [1, 2, 3, 4, 5, 6]

mul = lambda lst, val: [i * val for i in lst]
add = lambda lst, val1, val2: [i + val1 + val2 for i in lst]

mul10 = partial(mul, val=10)
add_10_100 = partial(add, val1 = 10, val2 = 100)
print add_10_100(mul10(lst))

[120, 130, 140, 150, 160, 170]

Solution 3:

Instead of reinventing numpy, use it!

import numpy as np

lst = np.arange(1, 7)
print lst * 10 + 10 + 100
[120130140150160170]

Post a Comment for "Applying A Series Of Functions To A List"