我有一个XML文件,其中包含许多点以及它们的经度和纬度。
目前,我的python代码通过简单地循环遍历XML文件,找到最近的点,然后将其与上一个最近的点进行比较,从而获得最近的点。如果它更接近,那么我将这个新点的值赋给变量。因此,在这方面一切都在发挥作用。
现在,我想要做的是存储最接近的2或3个点。我该怎么做呢?XML文件不是按最接近的顺序排序的,此外,每次发出请求时,用户位置都会发生变化。我能用XML文件做到这一点吗?或者我可能不得不考虑将数据存储在SQL Server或MySQL中?
谢谢你的帮助。PS,如果有人感兴趣的话,示例代码是available here。这是一个大学项目的一部分。
发布于 2011-04-23 05:26:50
在解析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?
..................发布于 2011-04-23 04:53:21
这是一个适用于任意数量的点的解决方案:
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成员。
https://stackoverflow.com/questions/5759847
复制相似问题