简体   繁体   English

在二维数组中查找给定特定坐标的邻居

[英]Find neighbors given a specific coordinate in a 2D array

I am trying to solve a problem using python and this is my first time to write python so I hope you could help me out.我正在尝试使用 python 解决一个问题,这是我第一次写 python 所以我希望你能帮助我。 I have a 2D array its values is -1,0,1 what I want to do is take the co-ordinates of a specific element and get the co-ordinates of all the adjacent elements我有一个二维数组,它的值为-1,0,1我想要做的是获取特定元素的坐标并获取所有相邻元素的坐标

Matrix = [[ 1,-1, 0],
          [ 1, 0, 0],
          [-1,-1, 1]]

for example if I have (0,0) so the function could return (0,1) , (1,0)例如,如果我有(0,0)那么 function 可以返回(0,1) , (1,0)

Since you want to work from the coordinates , a simple way I can think of is to define a grid graph using NetworkX and to look for the neighbours :由于您想从坐标开始工作,我能想到的一种简单方法是使用NetworkX定义网格图并查找neighbours

import networkx as nx
import numpy as np

a = np.array([[1,-1,0],
              [1,0,0],
              [-1,-1,1]])

G = nx.grid_2d_graph(*a.shape)
list(G.neighbors((0,0)))
# [(1, 0), (0, 1)]

Or for the "coordinates" of the middle value for instance:或者对于例如中间值的“坐标”:

list(G.neighbors((1,1)))
# [(0, 1), (2, 1), (1, 0), (1, 2)]

If you want to use them to index the array:如果要使用它们来索引数组:

ix = list(G.neighbors((0,0)))
a[tuple(ix)]
# array([ 1, -1])

It's not the best solution but it can help if you don't want to import any lib:这不是最好的解决方案,但如果您不想导入任何库,它会有所帮助:

def get_neighbors(matrix, x, y):
    positions = []
    positions.append(get_neighbor(matrix, x, y-1))
    positions.append(get_neighbor(matrix, x, y+1))
    positions.append(get_neighbor(matrix, x-1, y))
    positions.append(get_neighbor(matrix, x+1, y))

    return list(filter(None, positions))

def get_neighbor(matrix, x, y):
    if (x >= 0 and x < len(matrix[0])) and (y >= 0 and y < len(matrix[1])):
        return (x, y)

get_neighbors(your_matrix, x_position, y_position) get_neighbors(your_matrix, x_position, y_position)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM