简体   繁体   中英

How do I find the euclidean distance between two lists without using numpy or zip?

​​How do I find the euclidean distance between two lists without using either the numpy or the zip feature? Furthermore, the lists are of equal length, but the length of the lists are not defined.

For example:

ex 1. List 1 = [0, 5, 6]; List 2 = [1, 6, 8]

ex2. List 1 = [0, 1, 2, 3, 4]; List 2 = [5, 6, 7, 8, 9]

So far I have:

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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