I am trying to "invert" map (same function, multiple arguments) in a case where I have multiple function that I want to apply to the same argument. I am trying to find a more function approach to replace the classical
arg = "My fixed argument"
list_of_functions = [f, g, h] #note that they all have the same signature
[fun(arg) for fun in list_of_functions]
The only thing I could come up with is
map(lambda x: x(arg), list_of_functions)
which is not really great.
解决方案
You can try:
from operator import methodcaller
map(methodcaller('__call__', arg), list_of_functions)
The operator module also has similar functions for getting fixed attributes or items out of an object, often useful in functional-esque programming style. Nothing directly for calling a callable, but methodcaller is close enough.
Though, I personally like list comprehension more in this case. Maybe if there was a direct equivalent in the operator module, like:
def functioncaller(*args, **kwargs):
return lambda fun:fun(*args, **kwargs)
…to use it as:
map(functioncaller(arg), list_of_functions)
…then maybe it would be convenient enough?