将函数列表映射到参数列表 (Python)
Map a list of functions over a list of arguments (Python)
我有一个函数列表:listFunc=[g1, g2, g3]。此列表是使用以下代码生成的:
def g(y):
def f(x):
return x+y;
return f;
listFunc=list(map(g, [1, 2, 3]));
现在,我有一个参数列表 ListArg = [4, 5, 6];
如何仅使用 map
获得 [g1(4), g1(5), g1(6), g2(4), g2(5), g2(6), g3(4), g3(5), g3(6)]
的结果列表?
我考虑过使用以下代码:
map(lambda x:x(y), listFunc, ListArg)
但它只给出了[g1(4), g2(5), g3(6)]
的结果。
谢谢,
如果你想使用map()
,你可以这样做:
>>> [k for item in map(lambda x: [g(x) for g in listFunc], ListArg) for k in item]
[5, 6, 7, 6, 7, 8, 7, 8, 9]
你不能用 just map
完全做到这一点,但你可以将一个调用嵌套在另一个调用中,然后使用 sum
来展平结果.
>>> sum(map(lambda x : map(lambda f: f(x), ListArg),listFunc), [])
[5, 6, 7, 6, 7, 8, 7, 8, 9]
这是带有两个 for 子句的列表理解的完美用例:
>>> def g1(x): return 1*x
...
>>> def g2(x): return 2*x
...
>>> def g3(x): return 3*x
...
>>> funcs = [g1,g2,g3]
>>> args = [4,5,6]
>>> [f(a) for f in funcs for a in args]
[4, 5, 6, 8, 10, 12, 12, 15, 18]
>>>
这是非常可读和非常实用的 - 列表理解是从 Haskell 借来的。
如果您觉得需要使用地图,那么您将不得不像这样处理它:
>>> import itertools
>>> list(map(lambda f,a : f(a), *zip(*itertools.product(funcs,args))))
[4, 5, 6, 8, 10, 12, 12, 15, 18]
这显然 不可读 并且可能更慢。列表推导在这里获胜。
def g(y):
def f(x):
return x+y
return f
funcs = map(g, [1, 2, 3])
args = [4,5,6]
p = itertools.product(funcs, args)
r = [f(arg) for f, arg in p]
我能想到的列表理解的唯一替代方法是:
def foo(args):
f, a = args
return f(a)
r = list(map(foo, p)) # using p from above
我有一个函数列表:listFunc=[g1, g2, g3]。此列表是使用以下代码生成的:
def g(y):
def f(x):
return x+y;
return f;
listFunc=list(map(g, [1, 2, 3]));
现在,我有一个参数列表 ListArg = [4, 5, 6];
如何仅使用 map
获得 [g1(4), g1(5), g1(6), g2(4), g2(5), g2(6), g3(4), g3(5), g3(6)]
的结果列表?
我考虑过使用以下代码:
map(lambda x:x(y), listFunc, ListArg)
但它只给出了[g1(4), g2(5), g3(6)]
的结果。
谢谢,
如果你想使用map()
,你可以这样做:
>>> [k for item in map(lambda x: [g(x) for g in listFunc], ListArg) for k in item]
[5, 6, 7, 6, 7, 8, 7, 8, 9]
你不能用 just map
完全做到这一点,但你可以将一个调用嵌套在另一个调用中,然后使用 sum
来展平结果.
>>> sum(map(lambda x : map(lambda f: f(x), ListArg),listFunc), [])
[5, 6, 7, 6, 7, 8, 7, 8, 9]
这是带有两个 for 子句的列表理解的完美用例:
>>> def g1(x): return 1*x
...
>>> def g2(x): return 2*x
...
>>> def g3(x): return 3*x
...
>>> funcs = [g1,g2,g3]
>>> args = [4,5,6]
>>> [f(a) for f in funcs for a in args]
[4, 5, 6, 8, 10, 12, 12, 15, 18]
>>>
这是非常可读和非常实用的 - 列表理解是从 Haskell 借来的。
如果您觉得需要使用地图,那么您将不得不像这样处理它:
>>> import itertools
>>> list(map(lambda f,a : f(a), *zip(*itertools.product(funcs,args))))
[4, 5, 6, 8, 10, 12, 12, 15, 18]
这显然 不可读 并且可能更慢。列表推导在这里获胜。
def g(y):
def f(x):
return x+y
return f
funcs = map(g, [1, 2, 3])
args = [4,5,6]
p = itertools.product(funcs, args)
r = [f(arg) for f, arg in p]
我能想到的列表理解的唯一替代方法是:
def foo(args):
f, a = args
return f(a)
r = list(map(foo, p)) # using p from above