2015-09-26 41 views
5

我有一個列表:mylist = [1,2,5,4,7,8] 我已經定義了一些函數來操作這個列表。例如:從python中的函數列表中選擇函數的一個子集

def mean(x): ... 
def std(x): ... 
def var(x): ... 
def fxn4(x): ... 
def fxn5(x): ... 
def fxn6(x): ... 
def fxn7(x): ... 

現在我給出了一個我想應用於mylist的函數名列表。

爲前:fxnOfInterest = ['mean', 'std', 'var', 'fxn6']

什麼是最Python的方式來調用這些功能?

回答

6

我不認爲有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) 

在你的情況我會使用它的方式如下:

applyfs([mean, std, var, fxn4 ...], mylist) 

注意,你真的不需要使用函數名稱(正如您在PHP4中所做的那樣),Python函數本身是可調用的對象,可以存儲在列表中。

編輯:

或者,也許,這將是更Python使用列表理解,而不是map

results = [f(mylist) for f in [mean, std, var, fxn4 ...]] 
0

您可以使用eval

mylist = [1,2,5,4,7,8] 
fxnOfInterest = ['mean', 'std', 'var', 'fxn6'] 
for fn in fxnOfInterest: 
    print eval(fn+'(mylist)') 
3

你可以得到功能通過他們的名字與:

map(globals().get, fxnOfInterest) 

然後遍歷它們並把它們應用到列表:

[func(mylist) for func in map(globals().get, fxnOfInterest)] 
+0

優秀的答案,upvoted。如果需要檢查提供的名稱是否指向一個可調用的add if'hasattr(func,'__call __')'到列表理解(在python 3上使用'callable(func)') – Pynchia

0

試試這個例子,我想沒有什麼能比這更Python, 我把它叫做一個函數調度。

dispatcher={'mean':mean,'std':std,'var':var,'fxn4':fxn4} 
try: 
    for w in fxnOfInterest : 
     function=dispatcher[w] 
     function(x) 
except KeyError: 
    raise ValueError('invalid input') 

每次函數將根據dispatcher字典, 當你在羅馬做羅馬人一樣獲得價值。

+0

,即手動映射它們。但它是沒有必要的,因爲Python有許多內省的手段 – Pynchia

相關問題