我正在尝试编写一个给出整数矩阵的位置(x,y)的代码,我可以迭代距离K的所有邻居(左,右,上,下和对角线),这样:< / p>
K = 1
01 02 03 04 05 06
07 08 09 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
for i in range(M):
for j in range(N):
for ... #loop that i am writing... <br/>
#for (0,0) is [(0,0), (0,1), (1,0), (1, 1)]
#for (3, 3) is [(2,2), (2,3), (2,4), (3,2), (3,3), (3,4), (4,2), (4,3), (4,4)
这种方式适用于矩阵中的所有位置。
任何提示或代码?
答案 0 :(得分:1)
Numpy切片会让这很容易
>>> import numpy as np
>>> a = np.array(range(25)).reshape((5,5))
>>> print a
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
>>> k = 1
>>> a[2, 3]
13
>>> a[2-k:2+k+1, 3-k:3+k+1]
array([[ 7, 8, 9],
[12, 13, 14],
[17, 18, 19]])
Be careful of edge-cases, where index -1 will wrap to the other side of the array。