矩阵或列表列表中最近的“真”的数量

问题描述 投票:-8回答:1

在2D矩阵中,如何找到具有我正在搜索的值的邻居的数量?邻居被定义为8连接(垂直,水平和对角)

例如,在下面的例子中,对于矩阵中的每个元素X [i] [j],我想计算其中有多少个邻居具有值A

样本输入:

matrix = [[A, B, A], 
          [B, A, A],
          [B, A, B]]

样本输出:

solution   = [[1, 4, 2],
              [3, 4, 3],
              [2, 2, 3]]

例如。

  • matrix[0][0]有1个邻居,其值为A - > matrix[1][1]
  • matrix[0][2]有2个邻居,其值为A - > matrix[1][1]matrix[1][2]
python python-3.x list
1个回答
0
投票

绝对不是最好的方法,但它是有效的:

import numpy as np

mas1 = np.array([[True, False,  True],
       [ False,  True,  True],
       [ False,  True,  False]])

mas_answer = np.ndarray(shape=mas1.shape)

for i in range(mas1.shape[0]):
    for j in range(mas1.shape[1]):
        close_elt = []
        if i >= 1:
            try:
                close_elt.append(mas1[i-1,j])
            except:
                pass
            try:
                close_elt.append(mas1[i-1,j+1])
            except:
                pass

        if j >= 1:
            try:
                close_elt.append(mas1[i+1,j-1])
            except:
                pass
            try:
                close_elt.append(mas1[i,j-1])
            except:
                pass

        if i >= 1 and j >= 1:
            try:
                close_elt.append(mas1[i-1,j-1])
            except:
                pass

        try:
            close_elt.append(mas1[i,j+1])
        except:
            pass

        try:
            close_elt.append(mas1[i+1,j])
        except:
            pass
        try:
            close_elt.append(mas1[i+1,j+1])
        except:
            pass

        mas_answer[i,j] = close_elt.count(True)


# Ouput:
mas_answer
Out[27]: 
array([[1., 4., 2.],
       [3., 4., 3.],
       [2., 2., 3.]])
© www.soinside.com 2019 - 2024. All rights reserved.