简体   繁体   English

python计算距离最近的xy点

[英]python calculate distance closest xy points

so i have a list of points 所以我有一个要点清单

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

with a starting point of 起点为

["2.2 4.6"]

now what i am trying to do it is get the closest point to my starting point, then the closest point to that point and so on. 现在我正在尝试执行的操作是使最接近我的起点,然后最接近该点,依此类推。

So i get to calculate distance 所以我可以计算距离

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

but again, i'm trying to get the closest to my starting point, then the closest point to that one and so on. 但同样,我正在尝试最接近我的起点,然后最接近那个起点,依此类推。

ok, because you are complaing i didn't show enough code? 好的,因为您抱怨我没有显示足够的代码?

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

so i get passing my starting point I get 所以我通过了我的起点

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

So now i need to use 2.5, 3.6 as my starting point and find the next closest and so on 所以现在我需要使用2.5、3.6作为起点,并找到下一个最接近的点,依此类推

Has anyone done anything similar? 有人做过类似的事情吗?

A possibility is to use a breadth-first search to scan all elements, and find the closest point for each element popped off the queue: 一种可能性是使用广度优先搜索来扫描所有元素,并为从队列中弹出的每个元素找到最接近的点:

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"]))

Output: 输出:

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

The result is the listing of closest points, as determined by using math.hypot . 结果是通过使用math.hypot确定的最接近点列表。

You can try the following code. 您可以尝试以下代码。 Much simpler and short. 简单多了。 Uses a comparator to sort the list depending on the distance from the starting point (2.2,4.6) 使用比较器根据到起点的距离对列表进行排序(2.2,4.6)

import math
data = ["9.5 7.5", "10.2 19.1", "9.7 10.2", "2.5 3.6", "5.5 6.5", "7.8 9.8"]
data.sort(key=lambda x: math.sqrt((float(x.split(" ")[0]) - 2.2)**2 +
                                  (float(x.split(" ")[1]) -4.6)**2))
print(data)

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

You can simply sort a list by a key you define as you wish - fe by your distance function: 您可以简单地根据自己想要的键对列表进行排序 -fe通过距离函数进行排序

import math

def splitFloat(x):
    """Split each element of x on space and convert into float-sublists"""
    return list(map(float,x.split()))

def dist(p1, p2):
    # you could remove the sqrt for computation benefits, its a symetric func
    # that does not change the relative ordering of distances
    return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)

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

s = splitFloat("2.2 4.6")       # your start point
p = [splitFloat(x) for x in p]  # your list of points

# sort by distance between each individual x and s
p.sort(key = lambda x:dist(x,s))

d = [ (dist(x,s),x) for x in p]  # create tuples with distance for funsies
print(p)
print(d)

Output: 输出:

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

[(1.0440306508910546, [2.5, 3.6]), (3.8078865529319543, [5.5, 6.5]),
 (7.64198926981712, [7.8, 9.8]), (7.854934754662192, [9.5, 7.5]), 
 (9.360021367496977, [9.7, 10.2]), (16.560495161679196, [10.2, 19.1])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用距离矩阵在Python中计算经纬度点之间的距离 - Using distance matrix to calculate distance between points with latitude and longitude in Python xy点的测量结构 - python - Measure structure of xy points - python Python - 计算两个点列表(坐标)的最小欧氏距离 - Python - calculate minimum euclidean distance of two lists of points (coordinates) 如何计算 python 中线上两点之间的距离 - How to calculate the distance between two points on lines in python 使用 python 计算谷歌地图中两点之间的距离 - Calculate distance between 2 points in google maps using python 根据条件计算python中两点之间最近的邻居的距离 - Calculate distance of nearest neighbor in python between two points based on criteria 如何使用python计算数据点与聚类中心的距离 - how to calculate distance of data points from cluster centers using python 如何使用python中的返回方法计算两点之间的距离? - How to calculate the distance between two points using return methods in python? 替代(python)计算两个不同集合中所有点之间的距离 - Alternative (python) to calculate distance between all points at two different sets 计算二维网格上点之间的最短距离,Python - Calculate Shortest distance between points on a 2d grid, Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM