i have 2d list in python. given index want find neighbors of index. if list 3x3
given index (1, 1)
want return [(0, 1), (1, 0), (2, 1), (1, 2), (2, 2), (0, 0), (0, 2), (2, 0)]
if index (0, 0)
want return [(0, 1), (1,0), (1, 1)]
. know how ugly if statements. question is, there pretty pythonic magic 1 liner this?
a constant time solution 3x3 space example, list comprehensions :
valid={(x,y) x in range(3) y in range (3)} dirs=[(dx,dy) dx in (-1,0,1) dy in (-1,0,1) if (dx,dy)!=(0,0)] def voisins(x,y): return [(x+dx,y+dy) (dx,dy) in dirs if (x+dx,y+dy) in valid]