我有一个嵌套列表。示例:
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]]
答案 0 :(得分:0)
您可能想尝试一下:
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)