python多个函数有共同的参数_将多个函数应用于函数式Python中的相同参数

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?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值