温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Looking for a readable, elegant way to select direct neighbors in 2D list in Python

其他 - 寻找一种可读,优雅的方法在Python的2D列表中选择直接邻居

发布于 2020-03-27 10:56:18

我有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列表中获取直接邻居的一种可读,优雅的方法是什么?

查看更多

查看更多

提问者
Jonathan Esteban
被浏览
13
amdex 2019-07-03 22:06

如果要使用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

发布
问题

分享
好友

手机
浏览

扫码手机浏览