Python 如何使用 x 和 y 坐标循环遍历 2D numpy 数组而不会出现越界错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30499857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through 2D numpy array using x and y coordinates without getting out of bounds error?
提问by CompSci-PVT
I have tried the following:
我尝试了以下方法:
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]
This will only print numbers 1 - 6.
这只会打印数字 1 - 6。
I have also tried only subtracting 1 from either rows or cols in the range, but that either leads to out of bounds error or not all numbers printed.
我还尝试仅从范围内的行或列中减去 1,但这要么导致越界错误,要么未打印所有数字。
采纳答案by fouronnes
a.shape[0]
is the number of rows and the size of the first dimension, while a.shape[1]
is the size of the second dimension. You need to write:
a.shape[0]
是行数和第一个维度a.shape[1]
的大小,而是第二个维度的大小。你需要写:
for x in range(0, rows):
for y in range(0, cols):
print a[x,y]
Note how rows and cols have been swapped in the range()
function.
注意range()
函数中的行和列是如何交换的。
Edit: It has to be that way because an array can be rectangular (i.e. rows != cols). a.shape
is the size of each dimension in the order they are indexed. Therefore if shape
is (10, 5)
when you write:
编辑:必须这样,因为数组可以是矩形的(即行!= cols)。a.shape
是每个维度按照它们被索引的顺序的大小。因此,如果shape
是(10, 5)
当你写:
a[x, y]
the maximum of x is 9 and the maximum for y is 4.
x
and y
are actually poor names for array indices, because they do not represent a mathematical cartesisan coordinate system, but a location in memory. You can use i and j instead:
最大X的是9和Y的最大值为4
x
和y
实际上是数组索引差的名字,因为他们并不代表数学cartesisan坐标系,但在内存中的位置。您可以使用 i 和 j 代替:
for i in range(0, rows):
for j in range(0, cols):
print a[i,j]
The documentationis a bit long but has a good in-depth description of indices and shapes.
该文档是有点长,但具有指标和形状的一个很好的深入描述。
回答by Avión
You can use xrange
.
您可以使用xrange
.
for x in xrange(rows):
for y in xrange(cols):
print a[x,y]
回答by Markus Dutschke
You get prettier code with:
您可以通过以下方式获得更漂亮的代码:
for ix,iy in np.ndindex(a.shape):
print(a[ix,iy])
resulting in:
导致:
1
2
3
4
5
6
7
8
9
10
11
12