Python 存储3个最近的坐标

Python 存储3个最近的坐标,python,xml,gps,coordinates,geopy,Python,Xml,Gps,Coordinates,Geopy,我有一个XML文件,其中包含许多点及其经度和纬度 目前,我的python代码只需在XML文件中循环,找到最近的点,以英里或其他任何单位表示,然后将其与前一个最近的点进行比较,就可以得到最近的点。如果它更接近,那么我给变量分配这个新点的值。因此,在这方面,一切都在发挥作用 现在,我要做的是存储最接近的2或3个点。 我该怎么做呢?XML文件不是按最近者排序的,而且,每次发出请求时,用户的位置都会改变。我可以用一个XML文件来实现这一点吗?或者我可能需要考虑将数据存储在SQL Server或MySQL

我有一个XML文件,其中包含许多点及其经度和纬度

目前,我的python代码只需在XML文件中循环,找到最近的点,以英里或其他任何单位表示,然后将其与前一个最近的点进行比较,就可以得到最近的点。如果它更接近,那么我给变量分配这个新点的值。因此,在这方面,一切都在发挥作用

现在,我要做的是存储最接近的2或3个点。 我该怎么做呢?XML文件不是按最近者排序的,而且,每次发出请求时,用户的位置都会改变。我可以用一个XML文件来实现这一点吗?或者我可能需要考虑将数据存储在SQL Server或MySQL中吗

谢谢你的帮助。
PS,如果有人感兴趣,示例代码是。这是一个大学项目的一部分。

这里有一个解决方案,它适用于任何分数:

closest = points[:NUM_CLOSEST]
closest.sort()
for point in points[NUM_CLOSEST:]:
    if point.distance < closest[-1].distance:
        closest[-1] = point
        closest.sort()
closest=点[:NUM\u closest]
最近的。排序()
对于点中的点[NUM_CLOSEST:]:
如果point.distance<最近的[-1]。距离:
最近的[-1]=点
最近的。排序()

显然,有点假科迪。
sort()
调用可能需要一个参数,以便以一种有用的方式对它们进行排序,并且您可能需要一个函数来计算距离,以替换
distance
成员。

在解析de xml文件时,您应该将所有点对及其距离存储在元组列表中(例如)

mypoints = [(distance12, x1, x2),...,(distancenm, xn, xm)]
mypoints.sort()
three_closer = mypoints[:3]
使其适应您的代码:

..............
mypoints = []
for row in rows:
     # Get coords for current record
     curr_coords = row.getAttribute("lat") + ',' + row.getAttribute("lng")
     # Get distance
     tempDistance = distance.distance(user_coords, curr_coords).miles
     mypoints.append((tempDistance, row))

mypoints.sort()
#the three closest points:
mythree_shorter = mypoints[0:3]
for distance, row in mythree_shorter:
    shortestStation = json.dumps(
                            {'number': row.getAttribute("number"),
                             'address': row.getAttribute("address"),
                             'lat': row.getAttribute("lat"),
                             'lng': row.getAttribute("lng"),
                             'open': row.getAttribute("open")},
                             sort_keys=True,
                             indent=4)
    save_in_some_way(shortestStation)   #maybe writing to a file?
..................

谢谢你的帮助!我认为写入文件是不可行的,因为这些数据将被iPhone使用。我不太理解第二个for()循环。它怎么知道只有3个最近的?我假设它是在
mypoints[0:3]
中完成的,但我的python只是基本的。不管怎样,我都会测试一下,然后告诉你。谢谢你,华金!我用了你的一些代码,让它工作了!唯一缺少的是
shortestStation
上的“+=”,因此我现在使用的是
shortestStation=shortestStation+json.dumps()…
。再次感谢!!最近的三个存储在mythree_分拣机中,由回路按顺序取下。第二个for循环用于将序列化为json字符串的三个closer点保存到某个地方(列表、文件),或者将它们发送到某个地方(由您决定)…好的,我明白了。请注意:
以某种方式保存(shortestStation)shortestStation=shortestStation+json.dumps(…)
感谢您的回复!Sort()是正确的选择!