当给定一个n维矩阵和网格尺寸为1时,我想计算一个字段的最近邻。 以下是一个二维场地的示例:
P = (1,1)
p_neighbours = [(0,0),(2,2),(0,1),(0,2),(1,0),(2,0),(2,1),(1,2)]
从数学上讲,这可以在向量系统中轻松描述为P +/- 1(就我所知)。 n维邻居数组的大小描述为(n ^ 3)-1。我已经找到了一个相当不错的旧主题,但是我无法理解如何将任何提出的解决方案扩展到n维函数。
from itertools import product
def stencil(dim):
stencils = list(product([-1,0,1], repeat=dim))
zero = ((0,) * dim)
stencils.remove(zero)
return stencils
def neighbours(P):
stencils = stencil(len(P))
return [tuple([sum(x) for x in zip(P,s)]) for s in stencils]
P = (4, 4, 4)
print(neighbours(P))
我猜应该是这样的
p_neighbours = []
for x in [-1,0,1]:
for y in [-1,0,1]:
p_neighbours.append((P(0)+x,P(1)+y))
我认为这里最清晰的方法是使用简单的列表推导式:
p = (1,1)
px, py = p
p_neighbours = [(px+x,py+y) for x in range(-1,2) for y in range(-1,2) if (x,y) != (0,0)]
在这里,我们检查(x,y)不是(0,0),以避免将p本身加入其邻居。