如何在不带库的Python中找到两个向量之间的L1-Norm / Manhattan距离

问题描述

我有两个尺寸相等的向量,需要找到它们之间的距离

我尝试了各种方法:

sum([a-b for a,b in zip(u,v)]) 

c= sum([a-b for a,v)]
#If x is negative,multiply by negative one to convert x to a positive
if c<=0:
    return c*-1
#No changes are made to x if it is positive
else:
    return c

我还没有成功!

解决方法

您想使用abs()函数,该函数在标准python中可用。

如果有的话

a = [1,2,3,4,5,.4]
b = [4,-2,.8]

比你能得到的距离

sum([abs(i-j) for i,j in zip(a,b)])

我们可以使用sklearn实现来检查确实是正确的答案。

from sklearn.metrics.pairwise import manhattan_distances
manhattan_distances([a],[b])

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...