【问题标题】:Store 3 nearest coordinates存储 3 个最近的坐标
【发布时间】:2011-04-22 20:42:48
【问题描述】:

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

目前,我的 python 代码通过简单地遍历 XML 文件来获取最近的点,找到最近的点,以英里或其他为单位,然后将其与之前的最近点进行比较。如果它更接近,那么我将这个新点的值分配给变量。所以在这方面一切正常。

现在,我想要做的实际上是存储最接近的 2 或 3 个点。 我该怎么做呢? XML 文件不是按最近排序的,此外,每次发出请求时,用户的位置都会改变。我可以使用 XML 文件执行此操作吗,或者我可能需要考虑将数据存储为 SQL Server 还是 MySQL?

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

【问题讨论】:

    标签: python xml gps coordinates geopy


    【解决方案1】:

    在解析 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_sorter 中,并由循环按顺序获取。第二个 for 循环用于将序列化为 json 字符串的三个更接近的点保存在某处(列表、文件),或者将它们发送到某处(由您决定)...
    • 好的,我明白了。请注意:save_in_some_way(shortestStation) <=> shortestStation = shortestStation + json.dumps(...)
    【解决方案2】:

    这是一个适用于任意数量点的解决方案:

    closest = points[:NUM_CLOSEST]
    closest.sort()
    for point in points[NUM_CLOSEST:]:
        if point.distance < closest[-1].distance:
            closest[-1] = point
            closest.sort()
    

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

    【讨论】:

    • 感谢您的回复! Sort() 是要走的路!
    猜你喜欢
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多