2016-11-16 93 views
0

我试图运行下面的代码。对于那些了解它的人来说,这是Ehrenfest Urn模拟的尝试。阵列/矩阵操作出错

import numpy as np 
import random 

C=5 
L=2 
# Here I create a matrix to be filled with zeros and after with numbers I want 
b=np.zeros((L,C)) # line x column 

A=[] # here I creat 2 lists to put random integer numbers on it 
B=[] 

i=1 
while i<=10: # here I am filling list A (only) with 10 numbers 
    A.append(i) 
    i=i+1 

for j in range(2): 

    for i in range(5): #here I want to choose random numbers between 1 and 10, 

     Sort=random.randint(1,10) 

     if i==0: # since there is no number on B, the first step, the number goes to B 
      B.append(Sort) 
      A.remove(Sort) 
      print(len(A)) 

     if i>0: # now each list A and B have numbers on it, so I will choose one number and see in which list it is 
       if Sort in A: 
        B.append(Sort) 
        A.remove(Sort) 
       else: 
        A.append(Sort) 
        B.remove(Sort) 

      i=i+1 
      b[j,i]=len(A) # here I want to add the lenght of the list A in a matrix, but then I get the error. 
     j=j+1 

print(b) 

,但我得到了以下错误:

Traceback (most recent call last): 

    File "<ipython-input-26-4884a3da9648>", line 1, in <module> 
runfile('C:/Users/Public/Documents/Python Scripts/33.py', wdir='C:/Users/Public/Documents/Python Scripts') 

    File "C:\Program Files\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile 
execfile(filename, namespace) 

    File "C:\Program Files\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile 
exec(compile(f.read(), filename, 'exec'), namespace) 

    File "C:/Users/Public/Documents/Python Scripts/33.py", line 42, in <module> 
b[j,i]=len(A) # here I want to add the lenght of the list A in a matrix 

IndexError: index 5 is out of bounds for axis 1 with size 5 

我在做什么错的阵列? 与矩阵中的数字标识有什么关系?

+0

一个明显的问题是您的名单A []将有11个插槽,而不是10个(包括零);你对此有过解释吗? –

+0

是的,我确实检查了=)但我不知道问题出在哪里 –

+0

我相信Hpauji的答案应该可以工作 –

回答

1

该错误意味着b.shape[1](轴1)为5;但i是5.记住索引为0

开始在更广阔的画面:

while i<5: #here I want to choose random numbers between 1 and 10, 
    ... 
    i=i+1 
    b[j,i] ... 

在最后一次迭代i==4,你加一个,现在是5,并给出了错误。

通常在Python我们迭代与

for i in range(5): 
    b[j,i] ... 

range(5)产生[0,1,2,3,4]。您可能有充分的理由使用这个时间,但它受到相同的限制。

+0

哦,我不知道,谢谢!我改变了它在我的代码,但同样的错误再次出现 –

+0

哦,现在它工作了...我得到了与第一A.remove有关的另一个错误,但突然它的工作... –

+0

是否正常有不同的错误如果不更改代码并运行几次?我这样说是因为,我运行了代码5次,其中2次我在这里得到了同样的错误,其他次2次我得到了A.remove和上次运行的错误... –