konrad konrad - 3 months ago 15
Python Question

apply a function to a list and multiple single arguments

I have this definition that applies a function over a list of elements and a single additional argument that is needed for a function to execute. How can I modify it to apply arbitrary number of single arguments? Example:

Current method:

def ProcessListArg(_func, _list, _arg):
return map( lambda x: ProcessListArg(_func, x, _arg) if type(x)==list else _func(x, _arg), _list )


for that to work i need a function that takes two arguments. Ex:

def SomeFunction(arg1, arg2):
return something


I would apply it like so:

output = ProcessListArg(SomeFunction, inputArg1List, inputArg2)


I want to modify ProcessListArg to take advantage of multiple single arguments like so:

def SomeFunction2(arg1, arg2, arg3):
return something


Then I would apply it like so:

output = ProcessListArgs(SomeFunction2, inputArg1List, inputArg2, inputArg3)


I tried this:

def ProcessListArgs(_func, _list, *args):
return map( lambda *xs: ProcessListArgs(_func *xs) if all(type(x) is list for x in xs) else _func(*xs), *args)


That throws an error that argument is not iterable.

Thanks!

Answer

I believe this does what you want.

def SomeFunction(arg1, arg2):
    print "SomeFunction", arg1, arg2


def SomeFunction2(arg1, arg2, arg3):
    print "SomeFunction", arg1, arg2, arg3


def ProcessListArg(_func, _list, *_arg):
    return map(lambda x: ProcessListArg(_func, x, *_arg)
               if type(x) == list else _func(x, *_arg),
               _list)


ProcessListArg(SomeFunction, [1, 2, [2.1, 2.2, 2.3], 3], 4)
ProcessListArg(SomeFunction2, [1, 2, [2.1, 2.2, 2.3], 3], 4, 5)
Comments