2017-03-10 57 views
-1

我shapes.txt是這樣的:蟒蛇在列表中找到最接近的值

shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence 
100-1-0_D,41.0180673531548,29.085973004423135,0 
100-1-0_D,41.018257549826984,29.085232584769567,1 
100-1-0_D,41.018438672415755,29.084250285389476,2 
100-1-0_D,41.018926081703704,29.082072721166206,3 
100-1-0_D,41.019004044993366,29.081607048036684,4 
100-1-0_D,41.018951184935545,29.08119023014186,5 
...There are thousands of lines like this 

我添加到列表「shapes.txt」用這種方法。

with codecs.open('/home/fatih/Desktop/10mart/deneme/shapes.txt', 'r+', encoding='utf8') as veridosya3: 
    reader3 = csv.reader(veridosya3, delimiter=',', quoting=csv.QUOTE_NONE) 
    for row3 in reader3: 
     shapestxt.append(row3) 

我有一些coordinat值(緯度,經度)。我需要從shapes.txt找到最接近的緯度,經度值並獲得其序列值。 我該怎麼做?

這個問題很清楚,所以Szabolcs已經很好地回答了。

+0

最接近什麼? –

回答

1

我用geopy計算兩個點之間的距離,所以試試吧:

import csv 
from geopy.distance import vincenty 

with open('tmp.txt', 'r') as csv_file: 
    reader = csv.DictReader(csv_file, delimiter=',') 
    fixed_coord = (41.49008, -71.312796) 
    fixed_id = '100-1-0_D1' 
    shapes = [{'distance': vincenty(fixed_coord, (shape['shape_pt_lat'], shape['shape_pt_lon'])).miles, 'sequence': shape['shape_pt_sequence'],} for shape in reader if shape['shape_id'] == fixed_id] 
    closest = min(shapes, key=lambda shape: shape['distance']) 
print closest 

這將輸出:

{'distance': 4887.556987553742, 'sequence': '5'}

進行分解: 我讀在csv.DictReader的文件中,因此通過其標題訪問每個值更加容易。

然後我創建了一個任意的fixed_coord

在我計算出shapes列表中每個座標的距離和順序後。

然後我通過每個形狀的distance鍵排序shapes列表,最後返回最近形狀的距離和序列值。

+0

@FatihAltun在形狀列表理解中增加了比較。看看它。 – Szabolcs

+0

@FatihAltun考慮在像我在編輯中那樣生成'最接近''min'的時候替換'sorted'。 – Szabolcs

+1

我會問這個比較,但我已經試過了,我做了,就像你一樣:)。非常感謝你的成功答案 –

0
from geopy.distance import vincenty 
import codecs, csv 

def get_smallest_distance(reference_coordonate, coordonates): 
    coordonates = [dict(coordonate, geodistance=vincenty((coordonate['lat'], coordonate['lng']), reference_coordonate).kilometers) for coordonate in coordonates] 

    return min(coordonates, key=lambda k: k['geodistance']) 

coordonates = [] 
shapestxt = [] 
path = '/home/dan/projects/python/tools/coordonates.txt' 

with codecs.open(path, 'r+', encoding='utf8') as veridosya3: 
    reader3 = csv.reader(veridosya3, delimiter=',', quoting=csv.QUOTE_NONE) 
    for row3 in reader3: 
     coordonates.append({'lat': float(row3[1]), 'lng': float(row3[2])}) 

reference_coordonate = (42.1, 28) # as an example 
print get_smallest_distance(reference_coordonate, coordonates)