【发布时间】:2019-05-12 10:48:37
【问题描述】:
我想获取 np.array 的所有邻居值。
数组看起来像:
x = np.array([ [1, 2, 3, 4 ],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16] ])
我拥有的是:
i = 2
j = 2
n = x[i,j-1], x[i,j], x[i,j+1], x[i-1,j], x[i+1,j], x[i-1,j-1], x[i+1,j+1], x[i+1,j-1], x[i-1,j+1]
这会返回(我想要的)
(10, 11, 12, 7, 15, 6, 16, 14, 8)
但也有错误,例如当我想要
的邻居值时i = 3
j = 3
这给了:
Exception has occurred: IndexError
index 4 is out of bounds for axis 1 with size 4
另一种说法是:
def find_neighbors(m, i, j, dist=1):
return [row[max(0, j-dist):j+dist+1] for row in m[max(0,-1):i+dist+1]]
和
n = find_neighbors(x, i, j)
这给了我一组邻居,但在我设置时也给了我不是所有的邻居
i = 0
j = 0
因为它只给我:
[array([1, 2]), array([5, 6])]
有人对此有解决方案吗?
谢谢!
【问题讨论】:
-
我认为这个解决方案更加pythonic:stackoverflow.com/questions/7442570/….
-
i=3和j=3的期望结果是什么? -
@VasilisG 应该是 ``` [16, 13, 15, 4, 1, 3, 12, 9, 11] ``` @dome 我看到了他们,但他们没有帮助跨度>
标签: python arrays list numpy neighbours