Reputation:
I have 3 functions (f1
, f2
and f3
) that each take an input and return a str
.
These functions are stored in a list in an order that is determined by settings in a program prior to receiving inputs. Their ordering may be different each time a program is run:
# User A's run:
funcs = [f1, f1, f2, f1, f3]
# User B's run:
funcs = [f3, f3, f2]
During program execution, a list of inputs will be generated that correspond the to ordering of funcs
. That is to say, the item type of each index in the list inputs
will be the correct type expected by the function at the corresponding index of funcs
:
# f1 expects int
# f2 expects float
# f3 expects str
funcs = [f1, f1, f2, f1, f3]
inputs = [0, 1, 3.14, 10, 'abc']
I need to map funcs
to inputs
element-wise and concatenate the resulting string. Currently I solve this by using zip
:
result = ''.join(f(i) for f, i in zip(func, inputs))
Is there another way to achieve this type of mapping or is zip
the ideal way?
Upvotes: 2
Views: 103
Reputation: 450
I think you can import FunctionType and map each function to each input directly (tried it with a list of lambdas and it does work):
from types import FunctionType
funcs = [f1,f1,f2,f1,f3]
inputs = [0, 1, 3.14, 10, 'abc']
"".join(map(FunctionType.__call__, funcs, inputs))
Upvotes: 1