user1728853
user1728853

Reputation: 2707

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, val2: [i + val1 + val2 for i in lst]
...

I would like to create a higher-order function that can take any number of functions, each with a variable number of arguments and then apply these function in order to the list. It might look something like this:

>>> functions([mul, (10)], [add, (10, 100)]
[120, 130, 140, 150, 160, 170]

How can I do this in python?

Upvotes: 2

Views: 111

Answers (3)

shx2
shx2

Reputation: 64378

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]

Upvotes: 4

Ned Batchelder
Ned Batchelder

Reputation: 376052

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]

def functions(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

def functions(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.

Upvotes: 4

shx2
shx2

Reputation: 64378

Instead of reinventing numpy, use it!

import numpy as np

lst = np.arange(1, 7)
print lst * 10 + 10 + 100
[120 130 140 150 160 170]

Upvotes: 0

Related Questions