首页 > 解决方案 > 如果距离小于 5,如何创建点之间距离的嵌套 FOR 循环并保存坐标?

问题描述

给定 2 个数组,我想将 array1 的坐标与 array2 进行比较,如果距离 <= 5,则打印坐标。我使用了下面的代码,但它没有打印正确的坐标。

def euclideanDistance(coordinate1, coordinate2):
    dist= pow(pow(coordinate1[0] - coordinate2[0], 2) + pow(coordinate1[1] - coordinate2[1], 2), .5)
    if dist <= 5:
        return (coordinate1, coordinate2)

coords= [[17, 268],[17, 396],[18, 243], [18, 548]]
coords1= [[16, 484],[17, 398],[17, 640],[18, 331]]
distances = []
for i in range(len(coords)-1):
    for j in range(i, len(coords1)):
        distances += [euclideanDistance(coords[i],coords1[j])]
        print(distances)
            

输出应该是:[17, 396], [17, 398]

标签: pythonarrays

解决方案


首先,该函数euclideanDistance仅在距离大于 5 时返回坐标。因此,由于您将函数的结果添加到数组中,因此在距离小于 5 时distances添加了一个元组。因此,我会返回或任何其他标志,以表明不小于或等于 5。None, NoneFalsedist

其次,我不遵循您的for循环的逻辑-为什么嵌套的 for 循环仅在之间的范围i和长度范围内运行coords1

第三,变量名应该有意义。

此外,您可以在此处查看数组之间的区别append()+操作。

因此,我会将代码更改为:

def euclideanDistance(coordinate1, coordinate2):
    dist = pow(pow(coordinate1[0] - coordinate2[0], 2) + pow(coordinate1[1] - 
coordinate2[1], 2), .5)
    if dist <= 5:
        return (coordinate1, coordinate2)
    return False


distances = []
first_cords= [[17, 268],[17, 396],[18, 243], [18, 548]]
second_cords= [[16, 484],[17, 398],[17, 640],[18, 331]]
for f_cord in first_cords:
    for s_cord in second_cords:
        if euclideanDistance(f_cord,s_cord) is not False:
            distances.append([f_cor,s_cord])
print(distances)

哪个打印:[[[17, 396], [17, 398]]]


推荐阅读