I have an array that looks like this:
[['A0' 'B0' 'C0']
['A1' 'B1' 'C1']
['A2' 'B2' 'C2']]
I would like to get B1's neighbors which are B0 , C1 , B2 , A1, along with their indices.
This is what I came up with:
import numpy as np
arr = np.array([
['A0','B0','C0'],
['A1','B1','C1'],
['A2','B2','C2'],
])
def get_neighbor_indices(x,y):
neighbors = []
try:
top = arr[y - 1, x]
neighbors.append((top, (y - 1, x)))
except IndexError:
pass
try:
bottom = arr[y + 1, x]
neighbors.append((bottom, (y + 1, x)))
except IndexError:
pass
try:
left = arr[y, x - 1]
neighbors.append((left, (y, x - 1)))
except IndexError:
pass
try:
right = arr[y, x + 1]
neighbors.append((right, (y, x + 1)))
except IndexError:
pass
return neighbors
This will return a list of tuples (value, (y, x)).
Is there a better way to do this without relying on try/except?