簡體   English   中英

使用 python 中的字典計算兩點之間的距離

[英]Calculating distance between two points using dictionary in python

我正在嘗試使用它們的坐標計算兩個位置之間的距離。 但是我不知道如何訪問坐標值,因為它們在字典中。

我對編碼非常陌生,並且不理解我發現的有關此問題的任何代碼,因為它對我來說太高級了。 我真的不知道從哪里開始。 我的主要 function 創建字典:(編輯)

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': ... }

字典是這樣的,所以鍵是名稱,然后坐標是值。 這是 function,到目前為止幾乎沒有任何內容:

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

基本上我只需要知道如何使用字典,因為我不知道如何獲取這些值,因此我可以使用它們來計算距離。 --> 如何從字典中搜索一個鍵並獲取我使用的值。 謝謝你回答我的愚蠢問題。 :)

好吧,您剛開始,這使您變得更加困難是正常的。

所以讓我們看看,你有一個 function 輸出一個字典,其中鍵是位置,值是坐標對。 首先讓我們談談您使用的數據類型。

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

我認為您的價值觀存在問題,它們似乎是一組字符串。 這對您的目標有兩個主要優勢。
首先,set 對象不支持索引,這意味着您無法訪問location_map['Location1'][0]來獲取第一個坐標。 試試這個會給你一個TypeError 相反,在創建 map 時使用元組將允許您進行索引。 您可以通過將坐標定義為tuple([longitude,latitude])而不是{longitude,latitude}來做到這一點。
其次,您的坐標似乎是字符串,為了對您的數據執行算術運算,您需要一個數字類型,例如整數或浮點數。 如果您將經度和緯度值作為字符串讀取,則可以使用float(longitude)float(latitude)進行轉換。

有多種方法可以做到,下面列出的很少:

# 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 文檔了解 go 以獲得更深入的知識。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM