Python3 如何检测和替换数组中的邻居

Python 3 how to detect and replace neighbors in array

我有一个嵌套列表。示例:

list=[[1,1,1,3,3,1,1],
      [2,1,1,2,1,1,2],
      [3,0,1,1,1,1,3],
      [1,7,1,8,1,0,1]]

我想识别和更改我在此列表中选择的点的相同邻居(左、右、上、下)。不使用 numpy 或其他包。

def findNeighbors(list, x, y):
    if 0 < x < len(list) - 1:
        xi = (0, -1, 1)
    elif x > 0:
        xi = (0, -1)
    else:
        xi = (0, 1)
    yi = (0, -1, 1) if 0 < y < len(list[0]) - 1 else ((0, -1) if y > 0 else (0, 1))
    for a in xi:
        for b in yi:
            if a == -1 and b == 0 or a == 0 and b == -1 or a == 0 and b == 1 or a == 1 and b == 0:
                list[x + a][y + b] = 'a'
                findNeighbors(list,x+a,y+b)
                return list

findNeighbors(list, 2, 3)

for i in list:
    print(i)

从第 2 行第 3 列开始,我想创建以下列表:

list= [[a,a,a,3,3,a,a],
       [2,a,a,2,a,a,2],
       [3,0,a,a,a,a,3],
       [1,7,a,8,a,0,1]]

您可能想试试这个:

def findNeighbors(list, x, y):
    value = list[x][y]
    list[x][y] = 'a'

    if 0 < x < len(list)-1:
        xi = (0, -1, 1)
    elif x > 0:
        xi = (0, -1)
    else:
        xi = (0, 1)
    yi = (0, -1, 1) if 0 < y < len(list[0]) - 1 else ((0, -1) if y > 0 else (0, 1))
    for a in xi:
        for b in yi:
            if (a == -1 and b == 0) or (a == 0 and b == -1) or (a == 0 and b == 1) or (a == 1 and b == 0):
                if list[x + a][y + b] == value and list[x+a][y+b] != 'a':
                    findNeighbors(list,x+a,y+b)