Match a list of functions above a list of arguments (Python)

I have a list of functions: listFunc = [g1, g2, g3]. This list is generated using the code below:

def g(y): 
    def f(x):
        return x+y;
    return f; 
listFunc=list(map(g, [1, 2, 3])); 

Now I have a list of arguments ListArg = [4, 5, 6];

How can I get a list of results [g1(4), g1(5), g1(6), g2(4), g2(5), g2(6), g3(4), g3(5), g3(6)]using only map?

I was thinking about using the following code:

map(lambda x:x(y), listFunc, ListArg)

But he gives a result [g1(4), g2(5), g3(6)].

Thank,

+4
source share
4 answers

This is an ideal use case for understanding a list with two sentences:

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

This is a superbly readable and highly functional list that has been borrowed from Haskell.

, :

>>> import itertools
>>> list(map(lambda f,a : f(a), *zip(*itertools.product(funcs,args))))
[4, 5, 6, 8, 10, 12, 12, 15, 18]

, , . .

+5

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]
+5

map, sum .

>>> sum(map(lambda x : map(lambda f: f(x), ListArg),listFunc), [])
[5, 6, 7, 6, 7, 8, 7, 8, 9]
+3

itertools.product

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
+3

Source: https://habr.com/ru/post/1659239/


All Articles