Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 单元二维表邻域的确定_Python_Matrix - Fatal编程技术网

Python 单元二维表邻域的确定

Python 单元二维表邻域的确定,python,matrix,Python,Matrix,我有一个列表,类似于 [[1,2,3,],[4,5,6,],[7,8,9]] 以图形方式表示为: 1 2 3 4 5 6 7 8 9 我正在寻找一种优雅的方法来检查单元格相邻区域的值,水平、垂直和对角。例如,[0][2]的邻居是[0][1]、[1][1]和[1][2]或数字2、5、6 现在我意识到,我可以做一次暴力攻击来检查每一个值: [i-1][j] [i][j-1] [i-1][j-1] [i+1][j] [i][j+1] [i+1][j+1] [i+1][j-1] [i-1][j+1]

我有一个列表,类似于

[[1,2,3,],[4,5,6,],[7,8,9]]

以图形方式表示为:

1 2 3
4 5 6
7 8 9
我正在寻找一种优雅的方法来检查单元格相邻区域的值,水平、垂直和对角。例如,[0][2]的邻居是[0][1]、[1][1]和[1][2]或数字2、5、6

现在我意识到,我可以做一次暴力攻击来检查每一个值:

[i-1][j]
[i][j-1]
[i-1][j-1]
[i+1][j]
[i][j+1]
[i+1][j+1]
[i+1][j-1]
[i-1][j+1]
但这很容易,我想我可以通过一些更优雅的方法学到更多。

以下是您的列表:

(x - 1, y - 1) (x, y - 1) (x + 1, y - 1)
(x - 1, y)     (x, y)     (x + 1, y)
(x - 1, y + 1) (x, y + 1) (x + 1, y + 1)
(x,y)的水平邻域是(x+/-1,y)

垂直邻域为(x,y+/-1)

对角邻域是(x+/-1,y+/-1)

这些规则适用于无限矩阵。
为了确保邻域适合有限矩阵,如果初始值(x,y)在边上,只需对邻域的坐标施加一个限制-矩阵大小。

没有更干净的方法可以做到这一点。如果确实需要,可以创建一个函数:

def top(matrix, x, y):
     try:
         return matrix[x][y - 1];
     except IndexError:
         return None

我不知道它在您看来有多优雅,但它似乎在没有任何硬编码的情况下工作。

这会生成所有索引:

for x_ in range(max(0,x-1),min(height,x+2)):
  for y_ in range(max(0,y-1),min(width,y+2)):
    if (x,y)==(x_,y_): continue
    # do stuff with the neighbours

>>> a=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> width=height=3
>>> x,y=0,2
>>> for x_ in range(max(0,x-1),min(height,x+2)):
...   for y_ in range(max(0,y-1),min(width,y+2)):
...     if (x,y)==(x_,y_): continue
...     print a[x_][y_]
... 
2
5
6
def neighboring( array ):
    nn,mm = len(array), len(array[0])
    offset = (0,-1,1) # 0 first so the current cell is the first in the gen
    indices = ( (i,j) for i in range(nn) for j in range(mm) )
    for i,j in indices:
        all_neigh =  ( (i+x,j+y) for x in offset for y in offset )
        valid = ( (i,j) for i,j in all_neigh if (0<=i<nn) and (0<=j<mm) ) # -1 is a valid index in normal lists, but not here so throw it out
        yield valid.next(), valid ## first is the current cell, next are the neightbors

for (x,y), neigh in neighboring( l ):
    print l[x][y], [l[x][y] for x,y in neigh]
def相邻(数组):
nn,mm=len(数组),len(数组[0])
offset=(0,-1,1)#0 first,因此当前单元格是gen中的第一个单元格
指数=((i,j)范围内的i(nn)范围内的j(mm))
对于指数中的i,j:
所有_neigh=((i+x,j+y)表示偏移量中的x表示偏移量中的y)

如果(0可能您正在检查一个数独框,如果框为nxn,当前单元格为(x,y),则开始检查:

startingRow = x / n * n;
startingCol = y/ n * n
#“板”的大小
X=10
Y=10
邻域=λx,y:[(x2,y2)表示范围(x-1,x+2)内的x2
适用于范围内的y2(y-1,y+2)
如果(-1

假设您有一个正方形矩阵:

from itertools import product

size = 3

def neighbours(cell):
    for c in product(*(range(n-1, n+2) for n in cell)):
        if c != cell and all(0 <= n < size for n in c):
            yield c
函数的作用可以可视化如下:


如果有人对选择直接(非对角)邻居的替代方法感到好奇,请看:

neighbors = [(x+a[0], y+a[1]) for a in 
                    [(-1,0), (1,0), (0,-1), (0,1)] 
                    if ( (0 <= x+a[0] < w) and (0 <= y+a[1] < h))]
neighbories=[(x+a[0],y+a[1]),用于in
[(-1,0), (1,0), (0,-1), (0,1)] 
if((0感谢您提供有关邻居的重要提示。以下是此问题的运行代码:

    def findNeighbours(l,elem):
    #This try is for escaping from unbound error that happens 
    #when we try to iterate through indices that are not in array
    try:
        #Iterate through each item of multidimensional array using enumerate
        for row,i in enumerate(l):
            try:
                #Identifying the column index of the givem element
                column=i.index(elem)
            except ValueError:
                continue
            x,y=row,column
    
    #    hn=list(((x,y+1),(x,y-1))) #horizontal neighbours=(x,y+/-1)
    #    vn=list(((x+1,y),(x-1,y))) #vertical neighbours=(x+/-1,y)
    #    dn=list(((x+1,y+1),(x-1,y-1),(x+1,y-1),(x-1,y+1))) #diagonal neighbours=(x+/-1,y+/-1)
        #Creating a list with values that are actual neighbors for the extracted index of array
        neighbours=[(x,y+1),(x,y-1),(x+1,y),(x-1,y),(x+1,y+1),(x-1,y-1),(x+1,y-1),(x-1,y+1)]
        #Creating a universe of indices from given array
        index_list=[(i,j) for i in range(len(l)) for j in range(len(l[i]))]
        #Looping through index_list and nested loop for neighbours but filter for matched ones
        # and extract the value of respective index
        return_values=[l[index[0]][index[1]] for index in index_list for neighbour in neighbours if index==neighbour]
        return return_values,neighbours
    except UnboundLocalError:
        return []

如果lambdas吓唬了你,你就在这里。但是lambdas让你的代码看起来很干净。@johniek_comp有一个非常干净的解决方案

k,l=(2,3)
x = (0,-1,+1)
y = (0,-1,+1)
cell_u = ((k+a,l+b) for a in x for b in y)
print(list(cell_u))

灵感来自前面的一个答案

可以使用min()和max()函数缩短计算时间:

width = 3
height = 3

[(x2, y2) for x2 in range(max(0, x-1), min(width, x+2)) 
                    for y2 in range(max(0, y-1), min(height, y+2))
                    if (x2, y2) != (x, y)]

您想要获取索引还是值?您想要一个可以对每个索引进行随机访问的函数,还是一个返回(val,neights,of,of,val)列表的函数结对?--仅仅获取索引对于一个优雅的解决方案来说太简单了,但是你真正想做的可能更有趣或者-我故意把这个问题留得相当笼统,这样人们就不会感到拘束了。@Kaizer.se:谢谢,我不确定它是哪一个,也懒得去查找或尝试它。+1这不是一个完整的解决方案,但有趣的是,这可能是搜索邻居的一种非常好的方法——这实际上不起作用。我正在做一个类似的解决方案,并意识到了这一点。负索引实际上用于按相反顺序查找索引。例如-1表示最后一个元素。我不明白这个答案,我将其与问题一起运行在Python2.7中的示例中,如何添加检查以确保坐标不超过矩阵的边界?如果“board”is
10201x10201
?@CF84:那么常数
X
Y
需要为它们指定不同的值。您对此有什么问题吗?您的观点是什么?@CDspace编辑如何偏离帖子的原始意图?如果您指的是一行,它仍然可以用一个普通字符写在一行上函数。此外,自上次编辑以来,它还不是一行。至少大写的X和Y变量应该更改,因为它们很难识别。您好,这看起来不错。但是对于行数和列数不等的矩阵,如2*4数组,又如何呢?
neighbors = [(x+a[0], y+a[1]) for a in 
                    [(-1,0), (1,0), (0,-1), (0,1)] 
                    if ( (0 <= x+a[0] < w) and (0 <= y+a[1] < h))]
    def findNeighbours(l,elem):
    #This try is for escaping from unbound error that happens 
    #when we try to iterate through indices that are not in array
    try:
        #Iterate through each item of multidimensional array using enumerate
        for row,i in enumerate(l):
            try:
                #Identifying the column index of the givem element
                column=i.index(elem)
            except ValueError:
                continue
            x,y=row,column
    
    #    hn=list(((x,y+1),(x,y-1))) #horizontal neighbours=(x,y+/-1)
    #    vn=list(((x+1,y),(x-1,y))) #vertical neighbours=(x+/-1,y)
    #    dn=list(((x+1,y+1),(x-1,y-1),(x+1,y-1),(x-1,y+1))) #diagonal neighbours=(x+/-1,y+/-1)
        #Creating a list with values that are actual neighbors for the extracted index of array
        neighbours=[(x,y+1),(x,y-1),(x+1,y),(x-1,y),(x+1,y+1),(x-1,y-1),(x+1,y-1),(x-1,y+1)]
        #Creating a universe of indices from given array
        index_list=[(i,j) for i in range(len(l)) for j in range(len(l[i]))]
        #Looping through index_list and nested loop for neighbours but filter for matched ones
        # and extract the value of respective index
        return_values=[l[index[0]][index[1]] for index in index_list for neighbour in neighbours if index==neighbour]
        return return_values,neighbours
    except UnboundLocalError:
        return []
k,l=(2,3)
x = (0,-1,+1)
y = (0,-1,+1)
cell_u = ((k+a,l+b) for a in x for b in y)
print(list(cell_u))
width = 3
height = 3

[(x2, y2) for x2 in range(max(0, x-1), min(width, x+2)) 
                    for y2 in range(max(0, y-1), min(height, y+2))
                    if (x2, y2) != (x, y)]