Python查找二维数组中节点周围邻居的列表

标签 python arrays nearest-neighbor

我一直在编写一个代码(Py 2.7),它生成一个元素数组,每个节点都分配一些随机数。现在,我希望列出周围元素,并找到最大值的索引。数组大小是可变的(我认为 col = 数组列大小)。我已经为每个节点分配了数字(我在下面将其称为“s”),以便我可以找到数组元素的二维索引。这是我写的

rn = s/col; cn = s%col;
b = [rr[rn,cn+1],rr[rn-1,cn+1],rr[rn-1,cn],rr[rn-1,cn-1],rr[rn,cn-1],rr[rn+1,cn-1],rr[rn+1,cn],rr[rn+1,cn+1]]
ma = max(b)
a = [i for i,j in enumerate(b) if j == ma]

是否有任何简短的方法可以找到邻居而无需对每个数组元素进行编号? (就像我使用 s 所做的那样)。

最佳答案

您可以使用numpy为了这。首先,我们创建一个随机 5x5 矩阵 M用于测试...

>>> M = np.random.random((5, 5))
>>> M
array([[ 0.79463434,  0.60469124,  0.85488643,  0.69161242,  0.25254776],
       [ 0.07024954,  0.84918038,  0.01713536,  0.42620873,  0.97347887],
       [ 0.3374191 ,  0.99535699,  0.79378892,  0.0504229 ,  0.05136649],
       [ 0.73609556,  0.94250215,  0.67322277,  0.49043047,  0.60657825],
       [ 0.71153444,  0.43242926,  0.29726895,  0.2173065 ,  0.38457722]])

现在我们从这个矩阵中取出一个切片,N ,持有某个中心元素的邻居 (x, y)

>>> x, y = 2, 2
>>> N = M[x-1:x+2, y-1:y+2]
>>> N
array([[ 0.84918038,  0.01713536,  0.42620873],
       [ 0.99535699,  0.79378892,  0.0504229 ],
       [ 0.94250215,  0.67322277,  0.49043047]])

我们现在可以获得一个新矩阵,显示原始矩阵 M 的哪些元素等于 max来自N

>>> M == N.max()
array([[False, False, False, False, False],
       [False, False, False, False, False],
       [False,  True, False, False, False],
       [False, False, False, False, False],
       [False, False, False, False, False]], dtype=bool)

现在我们可以使用numpy.where获取 True 元素的索引在这个矩阵中。 zip用于获取元组列表。

>>> zip(*np.where(M == N.max()))
[(2, 1)]

请注意,这些是原始矩阵 M 中的位置,即它们可能包含 N 中不存在的元组。或者,您可以仅获取 N 中的最大值。 ,但是您必须添加 x-1y-1作为之后的偏移量。

>>> zip(*np.where(N == N.max()))
[(1, 0)]

关于Python查找二维数组中节点周围邻居的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818889/

相关文章:

python - 我可以在 Python 中以编程方式访问 ulimit 和 sysctl.conf 变量吗?

javascript - 在 JSX 中使用不同的 View 渲染数组

algorithm - 类 Levenshtein 距离度量中的最近邻搜索

sql - PL/PGSQL 总是返回数组或数组列表

machine-learning - k-NN以及关于k值和决策边界的一些问题

python - 如何从 scikit-learn 中的 TfidfTransformer 获得最匹配的特征名称?

python - Django - 找出变量属于哪个模型

python - python 中的 os.read(0,) 与 sys.stdin.buffer.read()

javascript - 从值中更改具有一个属性的对象的键

arrays - 在PowerShell中比较两个更大的文本数组