2017-05-30 142 views
1

我想打印二維數組的元素:IndexError當試圖打印二維數組

import numpy as np 
sessional=np.array([[1,2],[3,4],[5,6]]) 
for i in sessional: 
     print (sessional[i]) 

但是,它會導致以下錯誤:

IndexError: index 3 is out of bounds for axis 0 with size 3 

我想看到下面的輸出:

[1,2] 
[3,4] 
[5,6] 

回答

0

這是因爲您在傳遞sessional數組的實際元素爲IND ex本身。如果您想要打印的數組的每個元素,你應該print (i)取代print (sessional[i])

import numpy as np 
sessional = np.array([[1,2],[3,4],[5,6]]) 
for i in sessional: 
     print (i) 

輸出:

[1 2] 
[3 4] 
[5 6] 

如果你真的想你所指定的格式,你可以使用字符串格式化你的print語句:

import numpy as np 
sessional = np.array([[1,2],[3,4],[5,6]]) 
for i in sessional: 
     print ("[{0},{1}]".format(i[0], i[1])) 

輸出:

[1,2] 
[3,4] 
[5,6]