2015-02-11 122 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