Python 将字典元素打印为路径列表
我正在尝试使用Floyd Warshall算法和networkx(Python)打印所有可能的路径。问题是,我不知道如何正确地做(可读,作为列表)。 我的图表中有以下路径:Python 将字典元素打印为路径列表,python,json,dictionary,networkx,floyd-warshall,Python,Json,Dictionary,Networkx,Floyd Warshall,我正在尝试使用Floyd Warshall算法和networkx(Python)打印所有可能的路径。问题是,我不知道如何正确地做(可读,作为列表)。 我的图表中有以下路径: X = nx.floyd_warshall(gra) Y = {a: dict(b) for a, b in X.items()} print(Y) 它返回这个: {(0, 0): {(0, 0): 0, (1, 0): 1, (0, 1): 1, (1, 1): 2, (0, 2): 2, (1, 2): 3}, (1,
X = nx.floyd_warshall(gra)
Y = {a: dict(b) for a, b in X.items()}
print(Y)
它返回这个:
{(0, 0): {(0, 0): 0, (1, 0): 1, (0, 1): 1, (1, 1): 2, (0, 2): 2, (1, 2): 3}, (1, 0): {(1, 0): 0, (0, 0): 1, (1, 1): 1, (0, 1): 2, (0, 2): 3, (1, 2): 2}, (0, 1): {(0, 1): 0, (0, 0): 1, (1, 1): 1, (0, 2): 1, (1, 0): 2, (1, 2): 2}, (1, 1): {(1, 1): 0, (1, 0): 1, (0, 1): 1, (1, 2): 1, (0, 0): 2, (0, 2): 2}, (0, 2): {(0, 2): 0, (0, 1): 1, (1, 2): 1, (0, 0): 2, (1, 0): 3, (1, 1): 2}, (1, 2): {(1, 2): 0, (1, 1): 1, (0, 2): 1, (0, 0): 3, (1, 0): 2, (0, 1): 2}}
如何将其转换为更可读的格式?例如,是否可以逐个打印所有可能的路径?我想要这样的输出:
[(0, 0), (1, 0)]
[(1, 0), (1, 1)]
[(0, 0), (1, 0), (1, 1)]
...
[(0, 0), (1, 0), (1, 1), (0, 1), (0, 2), (1, 2)]
{(0, 0):
{(0, 0): 0,
(1, 0): 1,
(0, 1): 1,
(1, 1): 2,
(0, 2): 2,
(1, 2): 3},
(1, 0):
{(1, 0): 0,
(0, 0): 1,
(1, 1): 1,
(0, 1): 2,
(0, 2): 3,
(1, 2): 2},
[......]
(0, 1): 2}}
或者,是否可以将它们打印为JSON(或类似的格式):
感谢…打印Json:
import json
a = {(0, 0): {(0, 0): 0, (1, 0): 1, (0, 1): 1, (1, 1): 2, (0, 2): 2, (1, 2): 3}, (1, 0): {(1, 0): 0, (0, 0): 1, (1, 1): 1, (0, 1): 2, (0, 2): 3, (1, 2): 2}, (0, 1): {(0, 1): 0, (0, 0): 1, (1, 1): 1, (0, 2): 1, (1, 0): 2, (1, 2): 2}, (1, 1): {(1, 1): 0, (1, 0): 1, (0, 1): 1, (1, 2): 1, (0, 0): 2, (0, 2): 2}, (0, 2): {(0, 2): 0, (0, 1): 1, (1, 2): 1, (0, 0): 2, (1, 0): 3, (1, 1): 2}, (1, 2): {(1, 2): 0, (1, 1): 1, (0, 2): 1, (0, 0): 3, (1, 0): 2, (0, 1): 2}}
def dict_key_convert(dic):
converted = {}
for key, item in dic.items():
if isinstance(item, dict):
sub_dict = dict_key_convert(item)
converted[str(key)] = sub_dict
else:
converted[str(key)] = item
return converted
# print(json.dumps(dict_key_convert(a), indent=2))
with open('temp.json', 'w') as file:
json.dump(dict_key_convert(a), file, indent=2)
函数的结果看起来像一张表,是邻接矩阵吗?不是真的。。。我有这本字典,里面有2,3,4…,n个节点之间的所有可能路径,我想打印每个可能的路径(比如,在两个绝热节点之间,然后是三个绝热节点,四个,…,直到最远的节点),看起来你需要应用算法从你的最小距离重建路线。是的。。。我刚刚考虑了另一个选项:是否可以将整个字典作为json打印?