简体   繁体   中英

numpy array traversal Error: IndexError: index 1 is out of bounds for axis 0 with size 1

numpy with shape (5,1) with the following elements:

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

how do you go about traversing through and printing each element? as follows:

1
2
3
4
5

Attempt

for row in range(N):
    for col in range(D):
        print(input_array[row][col])

Error

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

Your N, D values must be wrong. Either do

N, D = input_array.shape

and continue with your code, or directly

for row in input_array:
    for token in row:
        print(token)

According to the error, the N value is wrong. It should be [0] .

Calculating with numpy.ndarray.shape function should return correct value of rows and columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM