在二维列表中查找周围的元素
Find surrounding elements in a 2d list
所以我需要一个函数来 return 与二维列表的某个索引相邻的所有元素
arr = [
[1 , 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
]
def ray(arr: list, center: list, ray: int) -> list:
values = []
for index_y, value_y in enumerate(arr):
for index_x, value_x in enumerate(value_y):
if index_x - center[0] < ray and index_y - center[1] < ray:
values.append(value_x)
return values
print(ray(arr, [4,4], 1))
输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
这是不正确的,有人可以帮助我或告诉我为什么我的功能不起作用吗?
错误在于
if index_x - center[1] < ray and index_y - center[0] < ray:
如果要比较距离,则应使用绝对值。应该是
if (abs(index_x - center[1]) < ray) and (abs(index_y - center[0]) < ray):
所以我需要一个函数来 return 与二维列表的某个索引相邻的所有元素
arr = [
[1 , 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]
]
def ray(arr: list, center: list, ray: int) -> list:
values = []
for index_y, value_y in enumerate(arr):
for index_x, value_x in enumerate(value_y):
if index_x - center[0] < ray and index_y - center[1] < ray:
values.append(value_x)
return values
print(ray(arr, [4,4], 1))
输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25] 这是不正确的,有人可以帮助我或告诉我为什么我的功能不起作用吗?
错误在于
if index_x - center[1] < ray and index_y - center[0] < ray:
如果要比较距离,则应使用绝对值。应该是
if (abs(index_x - center[1]) < ray) and (abs(index_y - center[0]) < ray):