将一系列函数应用于列表

时间:2013-03-29 12:34:39

标签: python

我有一个如下所示的列表:

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

我想创建一个高阶函数,它可以接受任意数量的函数,每个函数都有可变数量的参数,然后将这些函数应用于列表。它可能看起来像这样:

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

我怎么能在python中做到这一点?

3 个答案:

答案 0 :(得分:4)

这样做你想要的:

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

产生

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

您可能希望以不同方式构建函数:

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

正如其他人所指出的那样:numpy旨在完成所有这些以及更多。

答案 1 :(得分:4)

使用链接functools.partial。如,

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]

答案 2 :(得分:0)

不要重新发明numpy,而是使用它!

import numpy as np

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