python - 如何在不使用 numpy 或 zip 的情况下找到两个列表之间的欧几里德距离?
问题描述
如何在不使用 numpy 或 zip 功能的情况下找到两个列表之间的欧几里德距离?此外,列表的长度相同,但列表的长度没有定义。
例如:
例如 1。
list_1 = [0, 5, 6]
list_2 = [1, 6, 8]
例 2。
list_1 = [0, 1, 2, 3, 4]
list_2 = [5, 6, 7, 8, 9]
到目前为止,我有:
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
推荐阅读
- git - 如何像从未创建过一样删除提交(但以下所有提交仍然发生)?
- icon-fonts - 由于 IE 的字体下载安全选项已禁用,材质图标字体无法正常工作
- java - 四舍五入为 5 的倍数
- vb.net - 更改列表框的颜色、突出显示、背景大小?
- php - 在 laravel 5.5 中突出显示搜索结果
- ios - UITextView 最后缺少文本?
- xamarin.ios - 用于 gps 权限文本警报的 Xamarin.ios 本地化
- redis - 如何为 redis set key 设置过期超时,仅用于第一个 key 保存?
- java - 使用 java mockito 模拟 string.equalsIgnoreCase(String)
- firebase - Firebase startAt String 只需要第一个字符