如何使用x和y坐标在2D numpy数组中循环而不会出现越界错误?

w6mmgewl  于 12个月前  发布在  其他
关注(0)|答案(4)|浏览(76)

我尝试了以下方法:

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
print a
rows = a.shape[0]
cols = a.shape[1]
print rows
print cols

for x in range(0, cols - 1):
    for y in range(0, rows -1):
        print a[x,y]

它只打印数字1到6。
我也尝试过只从范围内的行或行中减去1,但这要么会导致越界错误,要么不会打印所有数字。

tsm1rwdh

tsm1rwdh1#

你得到更漂亮的代码:

for iy, ix in np.ndindex(a.shape):
    print(a[iy, ix])

导致:

1
2
3
4
5
6
7
8
9
10
11
12
omtl5h9j

omtl5h9j2#

a.shape[0]是第一维的行数和大小,而a.shape[1]是第二维的大小。你需要写:

for x in range(0, rows):
    for y in range(0, cols):
        print a[x,y]

注意在range()函数中行和行是如何交换的。
编辑:它必须是这样的,因为数组可以是矩形的(即,rows!=)。a.shape是每个维度的大小,按它们被索引的顺序排列。因此,如果shape(10, 5),当你写:

a[x, y]

最大x是9,最大y是4。xy实际上是数组索引的糟糕名称,因为它们不表示坐标,而是内存中的位置。你可以用i和j来代替:

for i in range(0, rows):
    for j in range(0, cols):
        print a[i,j]

documentation有点长,但对索引和形状有很好的深入描述。

unhi4e5o

unhi4e5o3#

可以使用xrange

for x in xrange(rows):
    for y in xrange(cols):
        print a[x,y]
rhfm7lfc

rhfm7lfc4#

可以使用np.nditer

it = np.nditer(a, flags=['multi_index'])
for x in it:
    print("{} {}".format(x, it.multi_index))

标签:Iterating Over Arrays

相关问题