首页 > 解决方案 > 从循环更新值时,字典似乎有点偏离和缺失值

问题描述

所以我有一个区域列表和一个目标列表,我想要做的就是使用haversine获得离该目标最近的区域和距离它的距离。我遇到的问题是,当我得到最终的字典时,它并没有把所有的记录都放在里面,我怀疑有些东西没有被正确捕获,这使得顺序混乱,但很难弄清楚它在哪里。

这是我的代码,如果不是很清楚,请告诉我

#Main dictionary with results
center_dict = dict()
for index, row in targets.iterrows():
    #latitude and longitude columns for the targets
    p_lat = row[9]
    p_lon = row[10]
    #name of the target, to be primary key of dict
    name = row[0]
    distances = dict()
    #loop of the areas to map against
    for ind, r in pins.iterrows():
        #longitude and latitude data for those areas
        r_lat = r[2]
        r_lon = r[3]
        #calling haversine function that returns a distance in miles
        distance = haversine(p_lon, p_lat, r_lon, r_lat)
        #adding distance to the distances dict with the location name as a key
        distances[r[0]] = distance
    #taking minimum value from dict and the key for this
    closest = min(distances, key=distances.get)
    closest_value = min(distances.values())
    #adding the two above to the list as well as a unique id for them which is in the data
    center_dict[name] = {row[1], closest, closest_value}

标签: python

解决方案


推荐阅读