2011-04-22 74 views
0

我有一个XML文件,其中包含许多经度和纬度的点。商店3最近的坐标

我的Python代码此刻通过简单循环XML文件获取最近的点,找到最近的,以英里或其他任何值,然后将它与以前的最近点进行比较。如果它更接近,那么我将这个新点的值赋给变量。所以一切都在这方面发挥作用。

现在,我想要做的是实际存储最接近的2或3分。 我该如何去做这件事? XML文件不是按最接近的顺序排列的,此外,每次发出请求时,用户位置都会发生变化。我可以用XML文件来做这件事吗?或者我可能不得不考虑存储数据是SQL Server还是MySQL?

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

回答

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? 
.................. 
+0

感谢您的帮助!我不认为写入文件是可行的,因为这些数据将被iPhone使用。我不太理解第二个for()循环。它如何知道只能得到最近的3个?我假设它在'mypoints [0:3]'中完成,但我的python只是基本的。我会无论如何测试它,并让你知道。 – eoinzy 2011-04-22 22:41:38

+0

谢谢华金!我使用了一些你的代码,并使其工作!唯一缺少的是“最短站点”上的“+ =”,所以我现在拥有的方式是“最短站点=最短站点+ json.dumps()....”。再次感谢!! – eoinzy 2011-04-22 22:55:11

+1

最接近的三个存储在mythree_sorter中,并按循环顺序进行。第二个for循环是为了保存三个更接近的点,作为json字符串序列化(列表,文件),或者将它们发送到某处(取决于您)... – joaquin 2011-04-22 22:59:27

1

这里是一个将任何点数工作的解决方案:

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成员。

+0

感谢您的答复!排序()是要走的路! – eoinzy 2011-04-22 22:53:21