When given a matrix of n-dimension and a grid size of 1 I'd like to calculate the nearest neighbours of a field.
Given below is an example for a 2-dimensional field
P = (1,1)
p_neighbours = [(0,0),(2,2),(0,1),(0,2),(1,0),(2,0),(2,1),(1,2)]
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))