【问题标题】:Calculating distance between two points using dictionary in python使用python中的字典计算两点之间的距离
【发布时间】:2019-11-06 15:30:47
【问题描述】:

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

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

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

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

【问题讨论】:

  • This one 可能会有所帮助。
  • 您能否给我们a)创建dict的主要功能部分和b)type(dictionary [location1])的值?
  • 欧几里得距离在纬度/经度坐标上不是一个好主意:例如点(0, 90)(180, 90)在球体上完全相同的位置,但欧几里得距离返回180。请改用半正弦公式。

标签: python dictionary


【解决方案1】:

嗯,你刚开始,这会让你变得更加困难是正常的。

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

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

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

【讨论】:

    【解决方案2】:

    有多种方法可以做到,下面列出了几种:

    # option 1
    for i, v in data.items(): # to get key and value from dict.
        for k in v: # get each element of value (its a set)
            print (k)
    
    # option 2
    for i, v in data.items(): # to get key and value from dict.
        value_data = [k for k in list(v)] # convert set to list and put it in a list
        print (i, value_data[0], value_data[1]) # use values from here
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-21
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 2011-04-23
      相关资源
      最近更新 更多