TypeError:+:'dict'和'float'

时间:2017-12-24 17:19:02

标签: python dictionary

此代码的第26行给出了错误,但我无法修复它。请帮我搞清楚。 这是一行: path[road]['distance_from_start'] = path.get(road, {}).get('distance_from_start') + path.get(road, {}).get('distance_to_neighbor') 它应该找到的是地图中起点和目标目标之间的最短路径,其间有多个中间站点。

import math
def my_function(M, start, goal):
    frontier = set([start])
    expanded = set()
    chosen = start
    chosen_coordinates = M.intersections[chosen]
    goal_coordinates = M.intersections[goal]
    roads_to_choose = M.roads[chosen]
    path = {}
    while frontier != set():
        if chosen != goal:
            for road in roads_to_choose:
                if road not in expanded:
                    frontier.add(road)
                    path[road] = {}
                    path[road]['coordinate'] = {}
                    path[road]['roads'] = {}
                    path[road]['distance_to_goal'] = {}
                    path[road]['distance_to_neighbor'] = {}
                    path[road]['distance_from_start'] = {}
                    path[road]['g_plus_h'] = {}
                    path[road]['path_list'] = {}
                    path[road]['coordinate'] = M.intersections[road]
                    path[road]['roads'] = M.roads[road]
                    path[road]['distance_to_neighbor'] = math.sqrt(((M.intersections[road][0]-chosen_coordinates[0])**2) + ((M.intersections[road][1]-chosen_coordinates[1])**2))
                    path[road]['distance_from_start'] = path.get(road, {}).get('distance_from_start') + path.get(road, {}).get('distance_to_neighbor')
                    path[road]['distance_to_goal'] = math.sqrt(((goal_coordinates[0]-M.intersections[road][0])**2) + ((goal_coordinates[1]-M.intersections[road][1])**2))
                    path[road]['g_plus_h'] = path[road]['distance_from_start'] + path[road]['distance_to_goal']
                    path[road]['path_list'] = path[chosen]['path_list'].append(road)
            frontier.remove(chosen)
            expanded.add(chosen)
            if x not in expanded:
                chosen = min(path.keys(), key=lambda x:path[x]['g_plus_h'])
                path[road]['distance_from_start'] = path.get(chosen, {}).get('distance_from_start')
        else:
            print("Short path called")  
            return path[goal]['path_list']

1 个答案:

答案 0 :(得分:0)

您正在尝试添加两个字典项:

x={}
y={}
z = x+ y

这是错误的方法,这就是为什么你会收到这个错误。究竟你想用这两个dictonary做什么,你的结果取决于那个。如果你想合并它们,那么试试这个:

在Python 3.5或更高版本中,:

z = {**x, **y}

在Python 2中,(或3.4或更低版本)编写一个函数:

def merge(x, y):
    z = x.copy()   
    z.update(y)   
    return z
z = merge(x, y)

通过查看代码,可以通过更改开头的分配来解决问题,更改

path[road]['distance_to_neighbor'] = 0
path[road]['distance_from_start'] = 0

然后你就能得到你的结果。