简体   繁体   English

在二维列表中查找周围的元素

[英]Find surrounding elements in a 2d list

So I need a function to return all elements neighbouring a certain index for a 2d list所以我需要一个函数来为二维列表返回与某个索引相邻的所有元素

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

Output: [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] it's incorrect, can someone help me or tell me why my function is not working ?输出: [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] 这是不正确的,有人可以帮助我或告诉我为什么我的功能不起作用吗?

The error lies in错误在于
if index_x - center[1] < ray and index_y - center[0] < ray:
If you're comparing distances, you should use absolute values.如果要比较距离,则应使用绝对值。 It should've been应该是
if (abs(index_x - center[1]) < ray) and (abs(index_y - center[0]) < ray):

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

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