我有一个列表:mylist = [1,2,5,4,7,8]
我已经定义了许多在此列表上运行的函数.例如:
def mean(x): ...
def std(x): ...
def var(x): ...
def fxn4(x): ...
def fxn5(x): ...
def fxn6(x): ...
def fxn7(x): ...
Run Code Online (Sandbox Code Playgroud)
现在我给出了一个我要在mylist上应用的函数名列表.
对于前: fxnOfInterest = ['mean', 'std', 'var', 'fxn6']
调用这些函数的最pythonic方法是什么?
我不认为有一种pythonic™方法可以解决这个问题.但在我的代码中,这是一个非常常见的情况,所以我已经编写了自己的函数:
def applyfs(funcs, args):
"""
Applies several functions to single set of arguments. This function takes
a list of functions, applies each to given arguments, and returns the list
of obtained results. For example:
>>> from operator import add, sub, mul
>>> list(applyfs([add, sub, mul], (10, 2)))
[12, 8, 20]
:param funcs: List of functions.
:param args: List or tuple of arguments to apply to each function.
:return: List of results, returned by each of `funcs`.
"""
return map(lambda f: f(*args), funcs)
Run Code Online (Sandbox Code Playgroud)
在你的情况下,我将使用以下方式:
applyfs([mean, std, var, fxn4 ...], mylist)
Run Code Online (Sandbox Code Playgroud)
请注意,您实际上不必使用函数名称(例如,PHP4中必须这样做),Python函数本身就是可调用对象,可以存储在列表中.
编辑:
或者可能,使用列表理解而不是map:更加pythonic :
results = [f(mylist) for f in [mean, std, var, fxn4 ...]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |