问题描述
我有一个列表,比如
[[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'm looking for an elegant approach to check the value of neighbours of a cell, horizontally, vertically and diagonally. For instance, the neighbours of [0][2] are [0][1], [1][1] and [1][2] or the numbers 2, 5, 6.
现在我意识到,我可以做一个蛮力攻击检查每一个值:
Now I realise, I could just do a bruteforce attack checking every value a la:
[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]
但这很容易,我想我可以通过看到一些更优雅的方法来了解更多.
But thats easy, and I figured I can learn more by seeing some more elegant approaches.
推荐答案
# 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)]
我不知道这是否被认为是干净的,但是这个单行通过迭代它们并丢弃任何边缘情况为您提供所有邻居.
I don't know if this is considered clean, but this one-liner gives you all neighbors by iterating over them and discarding any edge cases.
这篇关于确定单元格二维列表的邻居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!