2

我有一个看起来像这样的列表:

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中做到这一点?

4

3 回答 3

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 旨在完成所有这些以及更多。

于 2013-03-29T12:42:23.010 回答
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]
于 2013-03-29T12:49:18.213 回答
0

与其重新发明numpy,不如使用它!

import numpy as np

lst = np.arange(1, 7)
print lst * 10 + 10 + 100
[120 130 140 150 160 170]
于 2013-03-29T12:41:57.610 回答