你如何在二维列表中找到一个项目的邻居?
How do you find the neighbours of an item in a 2D list?
[
[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
。我尝试了一种方法,我把它列成一个大清单并做了一些垃圾,但它崩溃了,tbh。如果有兴趣,这是代码:
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"))
列表可以是任意大小,并不总是正方形。
找到元素的行索引和列索引。然后,您可以定义要检查的行/列差异列表,以生成邻居的索引。最后,您可以遍历这些差异来找到邻居。
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']
基本上涉及两个步骤:
- 查找目标项的索引(如果有的话)。
- 确定其周围有效项的索引。
这是一个文字实现:
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)
# 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)
首先找到物品的位置。使用形状来确定阵列的边缘。确定具有邻居的行和列,但删除任何不存在的位置。然后删除项目位置。最后,检索邻居。
此代码假定数组中的所有项目都是唯一的,并且所请求的项目存在于数组中。
[
[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
。我尝试了一种方法,我把它列成一个大清单并做了一些垃圾,但它崩溃了,tbh。如果有兴趣,这是代码:
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"))
列表可以是任意大小,并不总是正方形。
找到元素的行索引和列索引。然后,您可以定义要检查的行/列差异列表,以生成邻居的索引。最后,您可以遍历这些差异来找到邻居。
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']
基本上涉及两个步骤:
- 查找目标项的索引(如果有的话)。
- 确定其周围有效项的索引。
这是一个文字实现:
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)
# 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)
首先找到物品的位置。使用形状来确定阵列的边缘。确定具有邻居的行和列,但删除任何不存在的位置。然后删除项目位置。最后,检索邻居。
此代码假定数组中的所有项目都是唯一的,并且所请求的项目存在于数组中。