2015-02-11 117 views
1

我不擅長編程,我一直在瘋狂地試圖弄清楚這一點。python - IndexError:列表索引超出範圍/劃分列表

我有一個程序來計算綁定能量存儲列表中的值。在某一點上一個名單是由一個不同的劃分,但我不斷收到此錯誤:

Traceback (most recent call last): 
    File "semf.py", line 76, in <module> 
    BpN = BpN(A, Z) 
    File "semf.py", line 68, in BpN 
    bper = B[i]/A[i] 
IndexError: list index out of range 

相關的代碼如下,遺憾有這麼多了:

A = 0.0 

def mass_A(Z): 
    """ 
    ranges through all A values Z, ..., 3Z+1 for Z ranging from 1 to 100 
    """ 
    a = 0.0 
    a = np.arange(Z, 3*Z+1) 
    return a 

def semf(A, Z): 
    """ 
    The semi-empirical mass formula (SEMF) calculates the binding energy of the nucleus. 
    N is the number of neutrons. 
    """ 
    i = 0 
    E = [] 
    for n in A: 
     # if statement to determine value of a5 
     if np.all(Z%2==0 and (A-Z)%2==0): 
      a5 = 12.0 
     elif np.all(Z%2!=0 and (A-Z)%2!=0): 
      a5 = -12.0 
     else: 
      a5 = 0 

     B = a1*A[i] - a2*A[i]**(2/3) - a3*(Z**2/A[i]**(1/3)) - a4*((A[i] - 2*Z)**2/A[i]) + a5/A[i]**(1/2) 
     i += 1 
    E.append(B) 
    return E 

def BpN(A, Z): 
    """ 
    function to calculate the binding energy per nucleon (B/A) 
    """ 
    i = 0 
    R = [] 
    for n in range(1,101): 
     bper = B[i]/A[i] 
     i += 1 
     R.append(bper) 
    return R 

for Z in range(1,101): 
    A = mass_A(Z) 
    B = semf(A, Z) 
    BpN = BpN(A, Z) 

好像不知何故,這兩個列表A和B的長度不一樣,但我不確定如何解決這個問題。

請幫忙。

謝謝

+1

多久,他們應該是什麼?順便說一句,我注意到你的範圍都從一開始。你知道'a [0]'是'a'的第一個元素,而'a [1]'是第二個? – Kevin 2015-02-11 20:42:17

+0

我注意到函數'BpN'帶參數'A'和'Z'。 'Z'沒有被使用,但是全局'B'是。如果你將'B'傳遞給'BpN',這樣會更好,所以你不需要依賴全局。 – 2015-02-11 20:46:36

回答

1

在Python中,列表索引從零開始,而不是從一開始。

很難確定沒有看到您的代碼完整,但range(1,101)看起來懷疑。如果列表中有100個元素,則循環的正確界限是range(0,100)或等效range(100)或更好的是range(len(A))

P.S.既然你已經在使用Numpy了,你應該考慮使用Numpy數組而不是使用列表和循環來重寫你的代碼。如果AB是numpy的陣列,整個麻煩的功能將變成:

return B/A 

(這是AB元素方面的分工。)

+0

非常感謝你用'range(100)'修復了這個問題,在我仔細研究之後,我很可能會用numpy數組重新編寫代碼,但是現在我只是試圖使它符合截止日期的功能。 – GeegMofo 2015-02-11 22:09:43

相關問題