python计算最近xy点的距离

标签 python

所以我有一个点列表

["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]

起始点为

["2.2 4.6"]

现在我想做的是获取距离起点最近的点,然后获取距离该点最近的点,依此类推。

所以我可以计算距离

def dist(p1,p2):
    return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)

但同样,我正在尝试最接近我的起点,然后是最接近该起点的点,依此类推。

好吧,因为你提示我没有显示足够的代码?

fList = ["2.5 3.6", "9.5 7.5", "10.2 19.1", "9.7 10.2",  "5.5 6.5", "7.8 9.8"]
def distance(points):
    p0, p1 = points
    return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)

min_pair = min(itertools.combinations(fList, 2), key=distance)
min_distance = distance(min_pair)

print min_pair
print min_distance

所以我通过了我的起点

([2.2, 4.6], [2.5, 3.6])

所以现在我需要使用 2.5、3.6 作为起点并找到下一个最接近的等等

有人做过类似的事情吗?

最佳答案

一种可能是使用广度优先搜索来扫描所有元素,并找到从队列中弹出的每个元素的最近点:

import re, collections
import math

s = ["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]
def cast_data(f):
   def wrapper(*args, **kwargs):
     data, [start] = args
     return list(map(lambda x:' '.join(map(str, x)), f(list(map(lambda x:list(map(float, re.findall('[\d\.]+', x))), data)), list(map(float, re.findall('[\d\.]+', start))))))
   return wrapper

@cast_data
def bfs(data, start, results=[]):
   queue = collections.deque([start])
   while queue and data:
     result = queue.popleft()
     possible = min(data, key=lambda x:math.hypot(*[c-d for c, d in zip(result, x)]))
     if possible not in results:
       results.append(possible)
       queue.append(possible)
       data = list(filter(lambda x:x != possible, data))
   return results

print(bfs(s, ["2.2 4.6"]))

输出:

['2.5 3.6', '5.5 6.5', '7.8 9.8', '9.7 10.2', '9.5 7.5', '10.2 19.1']

结果是使用 math.hypot 确定的最近点的列表。

关于python计算最近xy点的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50159610/

相关文章:

python - 无法从 get-pip.py 安装 pip

python - Pandas:在应用函数中获取分组索引

python - 将数据框列中每个单词的首字母大写

python - JSON 字段 postgres 喜欢

python - 在Docker容器上运行Tkinter

python - 如何将多类别数据框绘制为单个箱线图

python - 如何将一个词典列表添加到另一个词典列表?

Python Pandas 根据另一列对值进行分组和排除

python - docker-compose 卷未正确安装

php - 解析大型 XML 数据