python - 计算python中n维字段的邻居

标签 python math

当给定一个 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 我已经找到了一个很好的 old topic ,无论如何我不明白如何将所提出的任何解决方案扩展到 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))

关于python - 计算python中n维字段的邻居,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40292190/

相关文章:

java - Math.random 重复自身

math - Code Golf : Mathematical expression evaluator (that respects PEMDAS)

java - 证明 : why does java. lang.String.hashCode() 的实现与其文档相匹配?

python - 未安装错误: TfidfVectorizer - Vocabulary wasn't fitted

另一个字符串中包含一些通用 (foo) 字符的 Python 字符串

algorithm - 如何从四个可以平移或旋转的点中找到一个点的坐标?所有这些点形成一个刚体

math - 将圆的角度转换为以分钟为单位的时间

Python从不同文件导入不同结果

python - 在 python 中运行 shell 脚本

python - 排列数组 : Exclude NaN and assign lowest rank to highest number