确定单元二维列表的邻居 [英] Determining neighbours of cell two dimensional list

查看:67
本文介绍了确定单元二维列表的邻居的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表列表,类似

I have a list of lists, something like

[[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.

这篇关于确定单元二维列表的邻居的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆