我有2D列表,我想从(上,下,左,右)获得直接邻居,而我想知道这样做的最Python方式是什么。
我看过确定单元格二维列表的邻居,但是他们寻找直接邻居的一种解决方法对我而言不是这样:(让x,y是2D列表中的任何两个索引)
neighbors = [(x+a[0], y+a[1]) for a in
[(-1,0), (1,0), (0,-1), (0,1)]
如果有的话,我会这样做的:
neighbors = [(x+a,y+b) for a,b in
[(-1,0), (1,0), (0,-1), (0,1)]
或像这样:
neighbors = [(a,b) for a,b in
[(x-1,y), (x+1,y), (x,y-1), (x,y+1)]
但后者感觉有点硬编码。有什么想法吗?
编辑:正式化我的问题:从Python的2D列表中获取直接邻居的一种可读,优雅的方法是什么?
如果要使用numpy,则可以使用索引数组,其中包含相对于所需索引的邻居索引,然后将其添加到所需索引。我个人认为这很优雅,但是YMMV
这是一个例子:
import numpy as np
# A 5 * 5 grid
grid = np.arange(25).reshape(5, 5)
# A schematic representation of the grid
# 0, 1, 2, 3, 4
# 5, 6, 7, 8, 9
# 10, 11, 12, 13, 14
# 15, 16, 17, 18, 19
# 20, 21, 22, 23, 24
# We define how our neighbors relate to our index.
mask = np.array([[0, 1], [1, 0], [0, -1], [-1, 0]])
# Let's say we want the neighbors of [2, 2], which are 17, 11, 7, and 13
# Index marked with X, neighbors marked with O
# 0, 1, 2, 3, 4
# 5, 6, O 8, 9
# 10, O X O 14
# 15, 16, O 18, 19
# 20, 21, 22, 23, 24
desired_index = np.array([2, 2])
# We add the neighbor indices to the mask
neighbor_indices = desired_index + mask
# [[2, 3], [3, 2], [2, 1], [1, 2]]
# Index the array using the indices.
neighbors = grid[neighbor_indices[:, 0], neighbor_indices[:, 1]]
请注意,此示例并未解决超出范围的问题。具体来说,当给定的索引高于列或行的数目时,它将出错,并且对于小于0的索引将回绕。
desired_index = np.array([0, 0])
neighbor_indices = desired_index + mask
neighbors = grid[neighbor_indices[:, 0], neighbor_indices[:, 1]]
# Wrong
desired_index = np.array([4, 4])
neighbor_indices = desired_index + mask
neighbors = grid[neighbor_indices[:, 0], neighbor_indices[:, 1]]
# Error
棒极了。确实非常优雅。尽管我只处理小型的普通2D列表,所以使用numpy有点过分。我的问题确实更多是关于清楚表达我的意图。也许我只是想得太多。
如果您认为数组过大,则仍可以使用类似的方法使用列表。
[grid[desired_x + x, desired_y + y] for x, y in [[-1, 0], [0, -1], [1, 0], [0, 1]]]
看起来有些笨拙,但我认为您明白了。无论如何,我认为最初的想法很明确。