gpt4 book ai didi

python - 当方法返回时字典缺少键

转载 作者:太空宇宙 更新时间:2023-11-03 18:36:52 24 4
gpt4 key购买 nike

我有一些代码,可以在我创建的图上执行修改后的 BFS,并在每个节点存储一些路径信息。 BFS 运行完成后,我的代码将路径列表打包并返回。控制流程如下:

Executable->BFS(graph)->Package_Path_List(node)

这是package_path_list方法:

def package_path_list(self, end):
'''Packages the path list at the destination node
This method packages the path list for user display and returns the optimal
paths present at the destination node
'''
final_path_list = {}
dest_id = handler.TOPOLOGY_GRAPH.get_vertex(end.get_id())
for key, value in end.nodePathTable.items():
path = list(key)
# Append the destination’s ID to the end of each path
final_path_list[(path.append(dest_id))] = value
pfLogger.debug("Packaging path list: " + str(path) + ":" + str(value))
return (final_path_list)

hfs_pathfinder 方法调用:

testDict = dict(self.package_path_list(end))
pfLogger.debug("Returned Path List: " + str(testDict))
return(testDict)

问题是我的日志文件显示字典已创建并且在 package_path_list 方法中存在良好,并且 bfs_pathfinder 方法的日志正确显示了该值,但 key 显示为 None

以下是日志:

pathfinding:DEBUG:bfspathfinder:345:  Packaging path list: [1 connectedTo: ['2', '4'], 2    
connectedTo: ['1', '3'], 3 connectedTo: ['2', '4']]:[1536.0, 6.0, 18.0]

pathfinding:DEBUG:bfspathfinder:295: Returned Path List: {None: [1536.0, 6.0, 18.0]}

我在这里没有看到任何错误的引用分配。有人可以指出错误吗?我有什么遗漏的吗?

最佳答案

问题出在这里:

    final_path_list[(path.append(dest_id))] = value

当您追加到列表时,它会就地发生,并且返回 None不是列表。您需要执行以下两个步骤:

path.append(dest_id)
final_path_list[tuple(path)] = value

请注意,我将 path 转换为元组:列表是可变的,因此不能是字典键。

关于python - 当方法返回时字典缺少键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21399903/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com