如果有多个函数要应用于同一个参数,我将尝试"反转"map
(同一函数,多个参数)。我正试图找到一种功能更强大的方法来取代经典的
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
已经足够接近了。
不过,在这种情况下,我个人更喜欢列表理解。也许在operator
模块中有一个直接的等价物,比如:
def functioncaller(*args, **kwargs):
return lambda fun:fun(*args, **kwargs)
…将其用作:
map(functioncaller(arg), list_of_functions)
…那也许就足够方便了?
在Python 3中,map()
示例返回一个映射对象,因此只有在迭代时才会调用函数,这至少是懒惰的。