尝试打印2D数组时的IndexError

时间:2017-05-30 04:17:55

标签: python arrays numpy

我正在尝试打印2D数组的元素:

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]

1 个答案:

答案 0 :(得分:0)

这是因为您将sessional数组的实际元素作为索引传递给自身。如果要打印数组的每个元素,则应将print (sessional[i])替换为print (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]