[英]Finding valid neighbor indices in 2d array
I have a 2d list in Python. 我在Python中有一个二维列表。 Given an index I want to find all the neighbors of that index.
给定一个索引,我想找到该索引的所有邻居。 So if my list is
3x3
then given the index (1, 1)
I want to return [(0, 1), (1, 0), (2, 1), (1, 2), (2, 2), (0, 0), (0, 2), (2, 0)]
but if the index is (0, 0)
then I want to only return [(0, 1), (1,0), (1, 1)]
. 因此,如果我的列表是
3x3
则给定索引(1, 1)
我想返回[(0, 1), (1, 0), (2, 1), (1, 2), (2, 2), (0, 0), (0, 2), (2, 0)]
但是如果索引为(0, 0)
那么我只想返回[(0, 1), (1,0), (1, 1)]
。 I know how to do this with ugly if statements. 我知道如何使用丑陋的if语句执行此操作。 My question is, is there a pretty Pythonic magic one liner for this?
我的问题是,这是否有漂亮的Pythonic魔术贴?
a constant time solution for a 3x3 space for example, with list comprehensions : 例如,具有列表推导的3x3空间的固定时间解决方案:
valid={(x,y) for x in range(3) for y in range (3)}
dirs=[(dx,dy) for dx in (-1,0,1) for dy in (-1,0,1) if (dx,dy)!=(0,0)]
def voisins(x,y): return [(x+dx,y+dy) for (dx,dy) in dirs if (x+dx,y+dy) in valid]
How ugly is your current code? 您当前的代码有多丑? I can't think of any obvious ways to do this automagically, just doing it manually without trying to write fancy one liners I don't think it looks too bad:
我想不出任何明显的方法来自动地做到这一点,只是手动进行而无需尝试编写精美的衬板,我认为它看起来还不错:
def find_neighours(index, x_size, y_size):
neighbours = []
x1, y1, = index
for x_move in (-1, 0, 1):
for y_move in (-1, 0, 1):
if x_move == 0 and y_move == 0:
continue
x2, y2 = x1 + x_move, y1 + y_move
if x2 < 0 or x2 >= x_size:
continue
if y2 < 0 or y2 >= y_size:
continue
neighbours.append((x2, y2))
return neighbours
Outputs: 输出:
find_neighours((1, 1), 3, 3)
Out[2]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1), (2, 2)]
find_neighours((0, 0), 3, 3)
Out[3]: [(0, 1), (1, 0), (1, 1)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.