Skip to content Skip to sidebar Skip to footer

How To Pass Multiple Arguments To Map()?

Would you help me understand if it possible to call map with multiple arguments ? My goal is to calculate the following: numpy.mean(array,axis=1) numpy.var(array,axis=0) numpy.std(

Solution 1:

You can use functools.partial:

>>>from functools import partial>>>array = np.arange(12).reshape(3,4)>>>array
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>>func_list = [
        partial(numpy.mean, axis=1), 
        partial(numpy.var, axis=0), 
        partial(numpy.std, axis=None)
    ]
>>>print(*map(lambda x:x(array), func_list), sep='\n')
[1.5 5.5 9.5]
[10.66666667 10.66666667 10.66666667 10.66666667]
3.452052529534663

Another way:

>>> func_list = [(numpy.mean, numpy.var, numpy.std), 
                 ({'axis':1}, {'axis':0}, {'axis':None})]

>>> print(*map(lambda f,kw: f(array, **kw), *func_list), sep='\n')
[1.55.59.5]
[10.6666666710.6666666710.6666666710.66666667]
3.452052529534663

A slight variation of the above:

>>> func_list = [
        (numpy.mean, {'axis':1}), 
        (numpy.var, {'axis':0}), 
        (numpy.std, {'axis':None})
    ]
>>> print(*map(lambda f,kw: f(array, **kw), *zip(*func_list)), sep='\n')
[1.55.59.5]
[10.6666666710.6666666710.6666666710.66666667]
3.452052529534663

Solution 2:

You can specify the functions with a lambda expression:

defa(x): return numpy.mean(x,axis=1)
defb(x): return numpy.var(x,axis=0)
defc(x): return numpy.std(x,axis=None)

print ("{}\n{}\n{}".format(*[x(array) for x in [a,b,c]]))

in the lambda expression you can specify the arguments. If you have more informations you can specify this in the lambda expression as well. Example:

def a_1(x,y): numpy.std(x,axis=y)

But then you need to pass this arguments as well. For example in a tuple

func_1 = (a_1, None) #Functionname and attribute

Post a Comment for "How To Pass Multiple Arguments To Map()?"