首页 > 解决方案 > 我想编写一个函数 distance(x, y),它以两个向量作为输入并输出它们之间的距离

问题描述

计算(0,0)和(1,1)之间的距离我写了这段代码,但它一直在产生错误

def distance(x,y):
    for i,j in x,y:
        x=(x[i],x[j])
        y=(y[i],y[j])
        a=x[i], b=x[j], c=y[i], d=y[j]
        new_distance =((d-b)**2+(c-a)**2)**(1/2)
        return new_distance

print(distance((0,0),(1,1)))

错误是

TypeError                                 Traceback (most recent call last)
<ipython-input-419-502ff9d672fc> in <module>
      7         return new_distance
      8 
----> 9 print(distance((0,0),(1,1)))

<ipython-input-419-502ff9d672fc> in distance(x, y)
      3         x=(x[i],x[j])
      4         y=(y[i],y[j])
----> 5         a=x[i], b=x[j], c=y[i], d=y[j]
      6         new_distance =((d-b)**2+(c-a)**2)**(1/2)
      7         return new_distance

TypeError: cannot unpack non-iterable int object

你能帮我吗

标签: python

解决方案


把事情简单化

def dist(x1,y1,x2,y2):
    return ((x1-x2)**2+(y1-y2)**2)**0.5

def dist_vec(p1,p2):
    return dist(p1[0],p1[1],p2[0],p2[1])

print(dist_vec((0,0),(1,1)))

推荐阅读