代码之家  ›  专栏  ›  技术社区  ›  qbuffer

获取二维数组中最近的坐标

  •  2
  • qbuffer  · 技术社区  · 6 年前
    coordinates = [(-225.0, -299.5), (-150.0, 75.5), (0.0, 0.0), (225.0, 300.5)]
    
    xy = (-222.4, -204.5)
    

    最好的方法是什么,以便将给定值xy与二维坐标列表进行比较,并返回最近坐标的索引号?

    在本例中,xy将与坐标列表进行比较,从而返回最近的坐标(-225.0,-299.5),或者更理想地,返回索引号0。

    4 回复  |  直到 6 年前
        1
  •  2
  •   user2390182    6 年前

    你可以用 min key 功能。某物,例如:

    coordinates = [(-225.0, -299.5), (-150.0, 75.5), (0.0, 0.0), (225.0, 300.5)]
    xy = (-222.4, -204.5)
    
    dist = lambda x, y: (x[0]-y[0])**2 + (x[1]-y[1])**2
    min(coordinates, key=lambda co: dist(co, xy))
    # (-225.0, -299.5)
    
        2
  •  4
  •   The_Scan_Master    6 年前

    使用scipy.spatial.KDTree:

    from scipy import spatial
    import numpy as np
    coordinates = [(-225.0, -299.5), (-150.0, 75.5), (0.0, 0.0), (225.0, 300.5)]
    x = [(-222.4, -204.5)]
    distance,index = spatial.KDTree(coordinates).query(x)
    print(distance)
    print(index)
    

    kd-tree方法是O(N*log(N)),比蛮力方法快得多,蛮力方法需要O(N**2)时间才能获得足够大的N。

        3
  •  1
  •   Anto    6 年前

    您的问题相当于:如何使用自定义方法对Python列表进行排序以定义排序键。这可以在原始python中完成,而无需使用外部库。

    当使用 sorted() key

    从这里开始,您只需将关键点定义为自己的距离计算方法(此处使用点之间的距离):

    from math import *
    coordinates = [(-225.0, -299.5), (-150.0, 75.5), (0.0, 0.0), (225.0, 300.5)]
    xy = (-222.4, -204.5)
    results = sorted(coordinates, key= lambda v: sqrt(pow((v[0] - xy[0]), 2) + pow((v[1] - xy[1]), 2)))
    # Output : [(-225.0, -299.5), (-150.0, 75.5), (0.0, 0.0), (225.0, 300.5)]
    

    from scipy.spatial import distance 作为排序的关键参数。

        4
  •  0
  •   ilbuonmarcio    6 年前

    您可以简单地创建一个函数,该函数遍历坐标列表,并保留两点之间距离最小的坐标列表的索引(使用毕达哥拉斯定理)。

    但是,如果您需要外部模块提供的快速功能,而不是编写自己的,我不知道我已经使用的库已经具有该功能,因此我在这里没有帮助。