python在列表中找到最接近的值

时间:2017-03-10 12:33:30

标签: python python-2.7

我的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) 

我有一些协调值(lat,lon)。我需要从shapes.txt中找到最接近的lat,lon值并获取其序列值。 我怎么能这样做?

问题非常明确,所以Szabolcs已经很好地回答了这个问题。

2 个答案:

答案 0 :(得分:2)

我使用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列表中每个坐标的距离和顺序后。

然后我按每个形状的shapes键对distance列表进行排序,最后返回最接近的形状的距离和序列值。

答案 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)