简体   繁体   中英

How to find neighbors of element in matrix in python?

I need help with a function that's supposed to return all neighbors of element in a matrix, I can't use numpy because it's a project for school.

For example for given matrix:

m =  [ 11 12 13
       21 22 23
       31 32 33 ] 

I need get_neigbors(x,y) function that returns all of elements around the element m[x][y]. for example get_neighbors(1,1) is supposed to return [12, 21, 22] And please, no one liners.! Thanks.

You can use a list of dx,dy offsets from the position given and return values for which the relative position is within the matrix's index ranges.

def get_neighbours(m,x,y):
    rows, cols = range(len(m)),range(len(m[0]))
    offsets = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
    result = []
    for dy,dx in offsets:
        ny, nx = y-1+dy, x-1+dx
        if ny in rows and nx in cols:
            result.append(m[ny][nx])
    return result

output:

m =  [ [11, 12, 13],
       [21, 22, 23],
       [31, 32, 33] ]

print(get_neighbours(m,1,1)) # [12, 12, 22]

Note that, Python indexes are zero-based but your example assumes that (1,1) is the top-left corner, so I subtracted 1 from the parameter values to get actual indexes in the matrix. You also need to pass the matrix as parameter to the function in order to access its content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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