문제

다음과 같은 목록이 있습니다.

[[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]

하지만 그건 쉬운 일이고, 좀 더 우아한 접근 방식을 보면 더 많은 것을 배울 수 있다고 생각했습니다.

도움이 되었습니까?

해결책

# Size of "board"
X = 10
Y = 10

neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
                               for y2 in range(y-1, y+2)
                               if (-1 < x <= X and
                                   -1 < y <= Y and
                                   (x != x2 or y != y2) and
                                   (0 <= x2 <= X) and
                                   (0 <= y2 <= Y))]

>>> print(neighbors(5, 5))
[(4, 4), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5), (6, 6)]

이것이 깨끗한 것으로 간주되는지는 모르겠지만 이 단일 라이너는 이웃을 반복하고 엣지 케이스를 삭제하여 모든 이웃을 제공합니다.

다른 팁

MB ...

from itertools import product, starmap

x, y = (8, 13)
cells = starmap(lambda a,b: (x+a, y+b), product((0,-1,+1), (0,-1,+1)))

// [(8, 12), (8, 14), (7, 13), (7, 12), (7, 14), (9, 13), (9, 12), (9, 14)]
print(list(cells)[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

사용 itertools.product 그리고 Python 's 덕분에 감사합니다 수율 표현 그리고 스타 운영자, 기능은 예쁘다 마른 그러나 여전히 읽을 수 있습니다.

매트릭스 크기 3이 주어지면 (필요한 경우) 이웃을 list:

>>> list(neighbours((2,2)))
[(1, 1), (1, 2), (2, 1)]

기능이 다음과 같이 시각화 될 수 있습니다.

Function visualization

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 top(matrix, x, y):
     try:
         return matrix[x][y - 1];
     except IndexError:
         return None

누군가가 직접 (비 지질) 이웃을 선택하는 대안적인 방법에 대해 궁금한 점이 있다면 여기에서갑니다.

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))]

다음은 귀하의 목록입니다.

(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)가 가장자리에 있으면 이웃의 좌표에 한 가지 더 제한을 적용합니다 - 매트릭스 크기.

>>> import itertools
>>> def sl(lst, i, j):
    il, iu = max(0, i-1), min(len(lst)-1, i+1)
    jl, ju = max(0, j-1), min(len(lst[0])-1, j+1)
    return (il, iu), (jl, ju)

>>> lst = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> tup = 0, 2
>>> [lst[i][j] for i, j in itertools.product(*sl(lst, *tup)) if (i, j) != tup]
[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]

어쩌면 당신은 스도쿠 상자를 확인하고있을 것입니다. 상자가 NXN이고 현재 셀이 (X, Y) 인 경우 : 확인을 시작하십시오.

startingRow = x / n * n;
startingCol = y/ n * n

감사합니다 @JS_IS_BAD 이웃에 대한 큰 힌트. 이 문제에 대한 실행 코드는 다음과 같습니다

    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가 당신을 여기에 daunt하는 경우 당신은.

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))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top