python - 如果距离小于 5,如何创建点之间距离的嵌套 FOR 循环并保存坐标?
问题描述
给定 2 个数组,我想将 array1 的坐标与 array2 进行比较,如果距离 <= 5,则打印坐标。我使用了下面的代码,但它没有打印正确的坐标。
def euclideanDistance(coordinate1, coordinate2):
dist= pow(pow(coordinate1[0] - coordinate2[0], 2) + pow(coordinate1[1] - coordinate2[1], 2), .5)
if dist <= 5:
return (coordinate1, coordinate2)
coords= [[17, 268],[17, 396],[18, 243], [18, 548]]
coords1= [[16, 484],[17, 398],[17, 640],[18, 331]]
distances = []
for i in range(len(coords)-1):
for j in range(i, len(coords1)):
distances += [euclideanDistance(coords[i],coords1[j])]
print(distances)
输出应该是:[17, 396], [17, 398]
解决方案
首先,该函数euclideanDistance
仅在距离大于 5 时返回坐标。因此,由于您将函数的结果添加到数组中,因此在距离小于 5 时distances
添加了一个元组。因此,我会返回或任何其他标志,以表明不小于或等于 5。None, None
False
dist
其次,我不遵循您的for
循环的逻辑-为什么嵌套的 for 循环仅在之间的范围i
和长度范围内运行coords1
?
第三,变量名应该有意义。
此外,您可以在此处查看数组之间的区别append()
和+
操作。
因此,我会将代码更改为:
def euclideanDistance(coordinate1, coordinate2):
dist = pow(pow(coordinate1[0] - coordinate2[0], 2) + pow(coordinate1[1] -
coordinate2[1], 2), .5)
if dist <= 5:
return (coordinate1, coordinate2)
return False
distances = []
first_cords= [[17, 268],[17, 396],[18, 243], [18, 548]]
second_cords= [[16, 484],[17, 398],[17, 640],[18, 331]]
for f_cord in first_cords:
for s_cord in second_cords:
if euclideanDistance(f_cord,s_cord) is not False:
distances.append([f_cor,s_cord])
print(distances)
哪个打印:[[[17, 396], [17, 398]]]
。
推荐阅读
- node.js - 松弛文件上传中的 no_file_data 响应
- php - 常量表达式包含无效操作 - 不突出显示其他变量?
- python - 从 python 脚本在 bash 中运行 pdftk
- javascript - 填写所有必填字段后如何更改按钮值
- c++ - 使用 QT 如何在不读取整个文件的情况下删除文本文件中的第一行?
- spring - Spring Data MongoDB Reactive - 处理大量文档的 findAll?
- django - 不同 ContentType 的 CharField 选择
- apache-kafka - Schema-Registry 拒绝未更改的模式,因为它不兼容
- python - Windows 上的 Pycharm 中的 Matplotlib 支持失败
- python - 无法使用 python -m 调用工具执行