在Python中找到两个列表的点之间的最小距离

编程入门 行业动态 更新时间:2024-10-26 20:28:59
本文介绍了在Python中找到两个列表的点之间的最小距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个坐标列表:

s1 = [(0,0), (0,1), (1,0), (1,1)] s2 = [(3,2), (1,9)]

我想计算s1中每个点到s2中任何点的最小距离.例如结果应该如下.

I want to calculate the minimum distance of each point in s1 to any point in s2. e.g. the results should be as follows.

result = [3.60, 3.16, 2.82, 2.23]

问题:就执行时间而言,实现这一结果的最优化方法是什么?

Question: What is the most optimized way in terms of execution time, to achieve this result?

到目前为止,我已经尝试过了,但是执行时间并不令人满意:

So far I've tried this but the execution time is not promising:

import math def nearestDistance(boundary, p): minDistList = map(lambda b: (b[0] - p[0])**2 + (b[1] - p[1])**2, boundary) minDist2 = min(minDistList) return math.sqrt(float(minDist2)) d = [] for p in s1: d.append(nearestDistance(s2, p))

我是否应该更改s1和s2的结构(例如,代替点使用2d数组)?

Should I change the structure of s1 and s2 (instead of points use 2d arrays for example)?

推荐答案

最简单的方法可能是使用 scipy.spatial.distance.cdist :

The easiest way is probably to use scipy.spatial.distance.cdist:

import numpy as np from scipy.spatial import distance s1 = np.array([(0,0), (0,1), (1,0), (1,1)]) s2 = np.array([(3,2), (1,9)]) print(distance.cdist(s1,s2).min(axis=1)) # array([3.60555128, 3.16227766, 2.82842712, 2.23606798])

直接从s1中的任何点(也位于s2中)直接输出0可能会获得更高的速度.

Some more speed might be gained by directly outputting 0 for any point from s1 that is also in s2.

更多推荐

在Python中找到两个列表的点之间的最小距离

本文发布于:2023-07-27 23:17:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1225240.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最小   距离   两个   中找到   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!