繁体   English   中英

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

[英]Looking for a readable, elegant way to select direct neighbors in 2D list in Python

我有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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM