2017-04-09 51 views
1

我正在創建一個適合各種曲線數據的程序。我創造了一些它做定義擬合函數如下:如何在不使用exec的情況下在每次迭代中對for循環使用不同的函數?

for i in range(len(Funcs2)): 
    func = "+".join(Funcs2[i]) 
    func = func.format("[0:3]","[3:6]") 
    exec('def Trial1{0}(x,coeffs): return {1}'.format(i, func)) 
    exec('def Trial1{0}_res(coeffs, x, y): return y - Trial1{0} 
    (x,coeffs)'.format(i)) 

如何再調用這些函數創建的每個功能反過來。目前,我做如下:

for i in range(len(Funcs2)): 
    exec('Trial1{0}_coeffs,Trial1{0}_cov,Trial1{0}_infodict,Trial1{0}_ 
      mesg,Trial1{0}_flag = 
      scipy.optimize.leastsq(Trial1{0}_res,x02, args=(x, y), 
      full_output = True)'.format(i)) 

在這個循環中,每個創建函數被調用的loop.The問題的每一次迭代是,我有使用EXEC()做的,讓想我要做。這可能是不好的做法,並且必須有另一種方式來做到這一點。

而且,我不能使用超過numpy的,SciPy的其他圖書館和matplotlib

很抱歉的壞格式。該框只能使用很長的代碼行。

+0

'Func2'是如何定義的? – Daniel

+0

'Funcs2'的內容是什麼?首先,我懷疑你的第一個循環是一個好主意。 – chepner

+0

Funcs2是元組列表。每個元組包含3個字符串。我同意循環是一個壞主意,但我想不出另一種動態創建和命名函數的方法 – GaeafBlaidde

回答

4

函數是python中的第一類對象!你可以把它們放在像列表或元組這樣的容器中,遍歷它們,然後調用它們。 exec()或eval()不是必需的。

要使用函數作爲對象而不是調用它們,請省略括號。

EG:

def plus_two(x): 
    return x+2 
def squared(x): 
    return x**2 
def negative(x): 
    return -x 

functions = (plus_two, squared, negative) 
for i in range(1, 5): 
    for func in functions: 
     result = func(i) 
     print('%s(%s) = %s' % (func.__name__, i, result)) 

- >輸出

plus_two(1) = 3 
squared(1) = 1 
negative(1) = -1 
plus_two(2) = 4 
squared(2) = 4 
negative(2) = -2 
plus_two(3) = 5 
squared(3) = 9 
negative(3) = -3 
plus_two(4) = 6 
squared(4) = 16 
negative(4) = -4 
+0

謝謝你這真的很有幫助。 – GaeafBlaidde

+0

很高興幫助!與未來的蟒蛇好運。 –

+1

就我個人而言,我認爲使用f-字符串會使代碼更難理解,因爲f-字符串對於大多數讀者來說可能是陌生的。我認爲將函數調用和結果打印成單獨的語句(例如:result = func(i); print(...)')會更好,這將更清楚地表明您正在調用函數而不是依靠一些字符串處理巫術。 –

相關問題