Let's say I have a list like this:
[1, 2, 3, 4]
And a list of functions like this:
[a, b, c, d]
Is there an easy way to get this output? Something like zip
, but with functions and arguments?
[a(1), b(2), c(3), d(4)]
Let's say I have a list like this:
[1, 2, 3, 4]
And a list of functions like this:
[a, b, c, d]
Is there an easy way to get this output? Something like zip
, but with functions and arguments?
[a(1), b(2), c(3), d(4)]
Use zip()
and a list comprehension to apply each function to their paired argument:
arguments = [1, 2, 3, 4]
functions = [a, b, c, d]
results = [func(arg) for func, arg in zip(functions, arguments)]
Demo:
>>> def a(i): return 'function a: {}'.format(i)
...
>>> def b(i): return 'function b: {}'.format(i)
...
>>> def c(i): return 'function c: {}'.format(i)
...
>>> def d(i): return 'function d: {}'.format(i)
...
>>> arguments = [1, 2, 3, 4]
>>> functions = [a, b, c, d]
>>> [func(arg) for func, arg in zip(functions, arguments)]
['function a: 1', 'function b: 2', 'function c: 3', 'function d: 4']
arguments = [1, 2, 3, 4]
functions = [a, b, c, d]
def process(func, arg):
return func(arg)
results = map(process, functions, arguments)
define a function process
to do the job, and use map
to iterate the functions
with its arguments