简体   繁体   English

用给定列表计算欧氏距离

[英]Calculating Euclidean Distance With Given Lists

def distance(alist, blist):
    sum_of = 0
    for x in alist:
        for y in blist:
            ans = (x - y)**2
            sum_of += ans
    return (sum_of)**(1/2)
print(distance([1, 1, 3], [2, 2, 3])) #1.4142135623730951
print(distance([1, 2, 3], [2, 2, 3])) #1.0
print(distance([2, 2, 3], [2, 2, 3])) #0.0
print(distance([1, 1], [2, 2])) #1.4142135623730951

So I have a set of test cases which give me two lists with numbers. 所以我有一组测试用例,它给了我两个带数字的列表。 My task is to calculate the euclidean distance with the given lists. 我的任务是用给定的列表计算欧氏距离。 However, I am not getting the right results. 但是,我没有得到正确的结果。 I am instead getting 3.7416573867739413, 3.0, 2.0 and 2.0. 我得到了3.7416573867739413,3.0,2.0和2.0。 This is what I have so far, and I am not sure what I am doing wrong. 这是我到目前为止所做的,我不确定我做错了什么。

The problem is here: 问题出在这里:

   for x in alist:
      for y in blist:

So for each point in alist , you are visiting all points in blist . 因此,对于alist每个点,您将访问blist所有点。 For example, for alist = [1, 2, 3] and blist = [4, 5, 6] , this loop would generate pairs (1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6) But what you want to do is to look at only (1, 4), (2, 5), (3, 6) . 例如,对于alist = [1, 2, 3]blist = [4, 5, 6] ,此循环将生成对(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)但你想要做的只是看(1, 4), (2, 5), (3, 6) This can be achieved with the zip function. 这可以通过zip功能实现。 If you iterate over zip(alist, blist) , it will iterate over those points. 如果你遍历zip(alist, blist) ,它将迭代这些点。 You can confirm this by executing 您可以通过执行来确认

list(zip(alist, blist))
Out: [(1, 4), (2, 5), (3, 6)]

So if you change the nested loops with a single loop over zip, it will calculate the correct distance. 因此,如果您使用zip上的单个循环更改嵌套循环,它将计算正确的距离。

def distance(alist, blist):
    sum_of = 0
    for x, y in zip(alist, blist):
        ans = (x - y)**2
        sum_of += ans
    return (sum_of)**(1/2)


distance([1, 1, 3], [2, 2, 3])
Out: 1.4142135623730951

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

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