[英]Error with arrays/matrix operations
I am trying to run the following code. 我正在尝试运行以下代码。 For those who know it, this is a try of the Ehrenfest Urn simulation. 对于那些了解它的人,这是对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)
But I get the following error: 但是我收到以下错误:
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
What am I doing wrong with the arrays? 我对数组做错了什么? Is there anything to do with the identification of the numbers in the matrix? 与矩阵中数字的标识有关吗?
The error implies that b.shape[1]
(axis 1) is 5; 该错误表明b.shape[1]
(轴1)为5; but i
is 5. Remember indexing starts at 0. 但是i
是5。请记住,索引从0开始。
In the broader picture: 从更广泛的角度来看:
while i<5: #here I want to choose random numbers between 1 and 10,
...
i=i+1
b[j,i] ...
at the last iteration i==4
, you add one, and now it is 5, and gives the error. 在上一次迭代i==4
,您添加一个,现在为5,并给出错误。
Typically in Python we iterate with 通常在Python中,我们使用
for i in range(5):
b[j,i] ...
range(5)
produces [0,1,2,3,4]
. range(5)
产生[0,1,2,3,4]
。 You may have good reasons to use the while instead, but it's subject to the same bounds. 您可能有充分的理由改用while,但是它受到相同的限制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.