python - 我想编写一个函数 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
你能帮我吗
解决方案
把事情简单化
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)))
推荐阅读
- python - 过滤python字典中的前3个值
- php - 具有不同重定向的php登录页面
- c# - 使用 HttpClient、客户端证书和 WinHttpHandler 向 Apple Push Notification Service 发送 HTTP/2 请求会引发 HttpRequestException
- python - np.float64 和 python float (64) 中的精度差异
- elasticsearch - Metricbeat 没有找到任何 application_pool
- kubernetes - Helm 预安装作业在服务帐户之前创建
- ios - 从 Firebase 实时数据库中获取需要几秒钟 [已修改]
- php - Slim Php v3 查询字符串
- javascript - HERE 映射 javascript API 多个航点
- r - 如果所有值都是特定值,则删除一列