python

# 其他 - 寻找一种可读，优雅的方法在Python的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)]
``````

Jonathan Esteban

15
amdex 2019-07-03 22:06

``````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])

# [[2, 3], [3, 2], [2, 1], [1, 2]]
# Index the array using the indices.
neighbors = grid[neighbor_indices[:, 0], neighbor_indices[:, 1]]
``````

``````desired_index = np.array([0, 0])