将多个函数应用于函数式Python中的相同参数 [英] Apply multiple functions to the same argument in functional Python
问题描述
在尝试将多个函数应用于同一个参数的情况下,我试图反转" map
(相同的函数,多个参数).我正在尝试找到一种功能更强的方法来替代经典
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]
我唯一能想到的是
map(lambda x: x(arg), list_of_functions)
这不是很好.
推荐答案
您可以尝试:
from operator import methodcaller
map(methodcaller('__call__', arg), list_of_functions)
operator
模块还具有类似的功能,可用于获取固定属性或对象中的项,通常在功能式编程风格中很有用.不能直接调用可调用对象,但是 methodcaller
关闭足够.
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.
不过,在这种情况下,我个人更喜欢列表理解.也许operator
模块中有直接等效项,例如:
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)
...将其用作:
map(functioncaller(arg), list_of_functions)
...那也许足够方便吗?
…then maybe it would be convenient enough?
这篇关于将多个函数应用于函数式Python中的相同参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!