列出相邻的单元格

Lin*_*nda 3 python

我有一个带有id值的570 x 800矩阵.如果找到每个项目的相邻邻居,我想做什么.除非单元格沿边界,否则最大邻居数为8.在这种情况下,将有三个邻居.我想将邻居附加到列表中.当每个单元格都有x和y坐标时,我看到了用于查找邻居的帖子,这非常有用,但是如何在没有坐标的情况下修改代码.ids以字符串形式出现,因为我将它用作字典中的键.任何帮助,将不胜感激.

And*_*ker 6

假设你要做的是在矩阵上构造一个八连通网格,并且矩阵中项目的位置定义了x坐标和y坐标,你可以使用这样的东西:

def eight_connected_neighbours( xmax, ymax, x, y ):
    """The x- and y- components for a single cell in an eight connected grid

    Parameters
    ----------
    xmax : int
        The width of the grid

    ymax: int
        The height of the grid

    x : int
        The x- position of cell to find neighbours of

    y : int 
        The y- position of cell to find neighbours of

    Returns
    -------
    results : list of tuple
        A list of (x, y) indices for the neighbours    
    """
    results = []
    for dx in [-1,0,1]:
        for dy in [-1,0,1]:
            newx = x+dx
            newy = y+dy
            if (dx == 0 and dy == 0):
                continue
            if (newx>=0 and newx<xmax and newy >=0 and newy<ymax):
                results.append( (newx, newy) )
    return results
Run Code Online (Sandbox Code Playgroud)