如何在2D列表中找到项目的邻居?


[
[a,b,c,d],
[e,f,g,h],
[i,j,k,l]
]

例如。g接触b,c,d,f,h,j,k,l,a接触e,f,b。我试过一种方法,我列了一个大清单,做了一些垃圾,但它崩溃了。如果感兴趣的话,下面是代码:

import math
big_list = []
x= [
["a", "b", "c", "d", "e", "f"],
["g", "h", "i", "j", "k", "l"],
["m", "n", "o", "p", "q", "r"],
["s", "t", "u", "v", "w", "x"],
["y", "z", "1", "2", "3", "4"]
]
#def find_neighbours(num):
for y in x:
for element in y:
big_list.append(element)
def find_row(element):
columns = len(x)
loc = big_list.index(element)
exact_row = (loc)/columns
return(math.floor(exact_row))
def find_column(element):
row = find_row(element)
exact_column = x[row]
return(exact_column)
print(find_column("x"))

列表可以是任意大小,并不一定是正方形。

# How do you find the neighbours of an item in a 2D list?
import numpy as np

def neighbors(array, item):
item_loc = tuple(np.asarray(np.where(array == item)).T[0].tolist())
s = tuple(np.array(array.shape) - 1)
n = np.array([-1, 0, +1])
rows = item_loc[0] + n
cols = item_loc[1] + n
neighbor_loc = [
(x, y) for x in rows for y in cols if (0 <= x <= s[0]) & (0 <= y <= s[1])
]
neighbor_loc.remove(item_loc)
print(
f"The neighbors of {item} are {array[tuple(np.transpose(neighbor_loc))].tolist()}."
)

array = np.array(
[
["a", "b", "c", "d", "e", "f"],
["g", "h", "i", "j", "k", "l"],
["m", "n", "o", "p", "q", "r"],
["s", "t", "u", "v", "w", "x"],
["y", "z", "1", "2", "3", "4"],
]
)
item = "r"
neighbors(array, item)

首先找到项目的位置。使用该形状确定数组的边缘。确定有邻居的行和列,但删除不存在的任何位置。然后删除项目位置。最后,检索邻居。

这段代码假设数组中的所有项都是唯一的,并且被请求的项存在于数组中。

查找元素的行和列索引。然后,您可以定义要检查的行/列差异列表,以便生成邻居的索引。最后,您可以遍历这些差异以查找邻居。

from itertools import product
board = [
['a','b','c','d'],
['e','f','g','h'],
['i','j','k','l']
]
target = 'a'
DELTAS = [x for x in product((-1, 0, 1), repeat=2) if x != (0, 0)]
for row_idx in range(len(board)):
for col_idx in range(len(board[0])):
if board[row_idx][col_idx] == target:
row = row_idx
col = col_idx
break
neighbors = []
for row_delta, col_delta in DELTAS:
if 0 <= row + row_delta < len(board) and 0 <= col + col_delta < len(board[0]):
neighbors.append(board[row + row_delta][col + col_delta])
print(neighbors)

这个输出:

['b', 'e', 'f']

基本上包括两个步骤:

  1. 查找目标项目的索引(如果有)。
  2. 确定其周围有效项的索引

这是一个文字实现:

m = [['a', 'b', 'c', 'd', 'e', 'f'],
['g', 'h', 'i', 'j', 'k', 'l'],
['m', 'n', 'o', 'p', 'q', 'r'],
['s', 't', 'u', 'v', 'w', 'x'],
['y', 'z', '1', '2', '3', '4']]
width = len(m[0])
height = len(m)
target = 'a'
x = None
for y in range(height):
try:
x = m[y].index(target)
except ValueError:
continue
else:
break  # Found
if x is not None:
print(f'Target {target!r} found in position [{x}, {y}]')
else:
raise RuntimeError(f'Target {target!r} not found.')
neighbours = []
for j in range(y-1, y+2):
if -1 < j < height:
for i in range(x-1, x+2):
if -1 < i < width and (i, j) != (x, y):
neighbours.append((i, j))
print('neighbours:', neighbours)

最新更新