首页 > 解决方案 > 如何在不使用 numpy 或 zip 的情况下找到两个列表之间的欧几里德距离?

问题描述

​​如何在不使用 numpy 或 zip 功能的情况下找到两个列表之间的欧几里德距离?此外,列表的长度相同,但列表的长度没有定义。

例如:

例如 1。

list_1 = [0, 5, 6]
list_2 = [1, 6, 8]

例 2。

list_1 = [0, 1, 2, 3, 4]
list_2 = [5, 6, 7, 8, 9]

到目前为止,我有:

    def euclidean_distance(p1, p2):
        sum = 0
        #(I think I need a for loop, possibly nested? --> For x in... for y in...)
        ans = (x-y) ** 2
        sum += ans
        return (sum) ** (1/2)

标签: pythonlisteuclidean-distance

解决方案


I think you could simplify your euclidean_distance() function like this:

def euclidean_distance(p1, p2):
        return abs(p1- p2)

One solution would be to just loop through the list outside of the function:

for i in range(len(list_1)):
    print(euclidean_distance(list_1[i], list_2[i]))

Another solution would be to use the map() function:

for result in map(euclidean_distance, list_1, list_2):
    print(result)

For

list_1 = [0, 5, 6]
list_2 = [1, 6, 8]

this would give you the output:

1
1
2

推荐阅读