Python,在列表列表中搜索给定坐标中最近匹配的索引
我有一个列表,其中包含以下值:Python,在列表列表中搜索给定坐标中最近匹配的索引,python,list,matrix,Python,List,Matrix,我有一个列表,其中包含以下值: field = [[0, 0, 0, -1, 0, 0, 0, 0, 0, 0], [0, -1, 0, 0, 0, 0, 0, -1, 0, 0], [0, 0, 0, 0, -1, 0, 0, 0, -1, 0], [0, 0, -1, -1, -1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, -1, -1]] 我需要从给定坐标中
field = [[0, 0, 0, -1, 0, 0, 0, 0, 0, 0],
[0, -1, 0, 0, 0, 0, 0, -1, 0, 0],
[0, 0, 0, 0, -1, 0, 0, 0, -1, 0],
[0, 0, -1, -1, -1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, -1, -1]]
我需要从给定坐标中找到最接近的值-1
我设法得到了所有匹配项的索引
到目前为止,我的代码是:
x = 0
y = 4
value = -1
coordinates = field[x][y]
for i, row in enumerate(field):
for j, elem in enumerate(row):
if elem == value:
print(i,j)
例如,如果给定的坐标是(0,4),它应该返回与最近的值(-1)匹配的坐标(1,7)
提前谢谢
field = [[0, 0, 0, -1, 0, 0, 0, 0, 0, 0],
[0, -1, 0, 0, 0, 0, 0, -1, 0, 0],
[0, 0, 0, 0, -1, 0, 0, 0, -1, 0],
[0, 0, -1, -1, -1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, -1, -1]]
x = 2
y = 1
z = -1
def coords(field, x,y,z):
for i, row in enumerate(field[x:]):
for j, elem in enumerate(row):
if elem == z and j > y:
return i+x,j
coords(field,x,y,z)
输出
(2, 4)
为什么(2,1)应该与(2,4)匹配?(1,1)不是更近了吗?你能更清楚地解释这个模式吗?我不明白如果x=0,y=4,它应该返回(1,1)还是(1,7)?为了更好的澄清,编辑了这篇文章
for j, elem in enumerate(field[x][y:]):
if elem == z:
print(i,j)
return
for i, row in enumerate(field[x+1:]):
for j, elem in enumerate(row):
if elem == z:
print(i,j)
return