如果您不关心效率,请使用scipy:
import scipy, scipy.ndimage
def nb_vals(matrix, indices):
matrix = scipy.array(matrix)
indices = tuple(scipy.transpose(scipy.atleast_2d(indices)))
arr_shape = scipy.shape(matrix)
dist = scipy.ones(arr_shape)
dist[indices] = 0
dist = scipy.ndimage.distance_transform_cdt(dist, metric='chessboard')
nb_indices = scipy.transpose(scipy.nonzero(dist == 1))
return [matrix[tuple(ind)] for ind in nb_indices]
例如
>>> matrix=[[1,2,3,4],
... [5,6,7,8],
... [9,10,11,12]]
>>>
>>> nb_vals(matrix, [1,1])
[1,2,3,5,7,9,10,11]
这是与维度无关的(为输入“矩阵”的任意数量的维度工作)并处理您可能希望在附近找到邻居的任意数量的索引.
>>> arr_shape = (2,3,4,5)
>>> testMatrix = scipy.array(scipy.random.random(arr_shape)*10, dtype=int)
>>> print(testMatrix