在python中使用字典计算两点之间的距离

我正在尝试使用它们的坐标来计算两个位置之间的距离。但是我不知道如何访问坐标值,因为它们在字典中。

我对编码非常陌生,并且不了解有关此问题的任何代码,因为它对我来说太高级了。我真的不知道从哪里开始。我的主要功能是创建字典:(编辑)

def main():
    filename = input("Enter the filename:\n")
    file= open(filename,'r')
    rows= file.readlines()
    d = {}
    list = []
    for x in rows:

        list.append(x)
    #print(list)
    for elem in list:

        row = elem.split(";")

        d[row[3]] = {row[0],row[1]} #these are the indexes that the name and latitude & longitude have in the file

{'Location1':{'40 .155444793742276','28 .950292890004903'},'Location2':...}

字典就是这样,所以键是名称,然后坐标是值。这是该函数,到目前为止几乎不包含任何内容:

def calculate_distance(dictionary,location1,location2):

    distance_x = dictionary[location1] - dictionary[location2] 
    # Here I don't know how I can get the values from the dictionary,# since there are two values,longitude and latitude...

    distance_y = ...
    distance = ... # Here I will use the pythagorean theorem

    return distance

基本上,我只需要知道如何使用字典,因为我不知道如何获取这些值,因此可以使用它们来计算距离。 ->如何从字典中搜索键并获取值供我使用。感谢您回答我的愚蠢问题。 :)

yanlovey 回答:在python中使用字典计算两点之间的距离

好吧,这是正常现象,这会使您更加困难。

所以让我们看一下,您有一个输出字典的函数,其中的键是位置,值是坐标对。 首先,让我们谈谈您使用的数据类型。

location_map={'Location1': {'40.155444793742276','28.950292890004903'},'Location2': ... }

我认为您的值有问题,似乎它们是字符串集。这对于您的目标有2个主要优点。
首先,集合对象不支持索引,这意味着您无法访问location_map['Location1'][0]来获取第一个坐标。尝试此操作将给您TypeError。相反,在创建地图时使用元组将允许您建立索引。您可以通过将坐标定义为tuple([longitude,latitude])而不是{longitude,latitude}来实现。
其次,似乎您的坐标是字符串,为了对数据执行算术运算,您需要一个数字类型,例如整数或浮点型。如果您将经度和纬度值读取为字符串,则可以使用float(longitude)float(latitude)进行转换。

,

有多种方法可以完成,下面列出了几种方法:

require_once 'phpQuery/phpQuery/phpQuery.php';
$vin = "WBAUN1C57CVH84281";

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://autoastat.com/en/search');
curl_setopt($ch,CURLOPT_HEADER,false);

curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,CURLOPT_POSTFIELDS,'search_lot_by_identifier_form[field]='.$vin);
curl_setopt($ch,'search_lot_by_identifier_form[search]=');
curl_setopt($ch,'search_lot_by_identifier_form[_token]=H_eD0985LSPHy_dQRKGSwZnYZm3yMhVH4ehKo1pZgI0');

curl_setopt($ch,CURLOPT_HTTPHEADER,array('Content-Type: application/x-www-form-urlencoded'));
$out = curl_exec($ch);
curl_close($ch);

// var_dump($out);

$pq2 = phpQuery::newDocument($out);
var_dump($pq2);
die;

我建议您仔细阅读python文档以获得更深入的知识。

本文链接:https://www.f2er.com/3150895.html

大家都在问