用字典添加 networkx edgest

adding networkx edgest with a dictionary

我的数据结构如下:

{1: [2, 3, 4, 5, 6, 7, 8, 10, 12], 8: [9], 14: [15, 17, 19, 20]}

字典的键是父项,后面的列表是子项。 我想将边缘添加到 Networkx DAG。

我知道我可以创建一个元组列表:

edges=[]
for parent,children in dic.items():
    for child in children:
        edges.append((parent,child))

[(2,1)(3,1)(4,1)  ...etc]

然后将元组添加为:

G.add_edges_from([(2,1)(3,1)(4,1) ....])

有什么方法可以更直接地添加边,而不必重构我原来的数据结构?

谢谢

编辑: 此列表理解无法正常工作:

[(parent,child) for child in children for parent,children in dic.items()]

鉴于您正在创建无向图,请使用:

import networkx as nx

d = {1: [2, 3, 4, 5, 6, 7, 8, 10, 12], 8: [9], 14: [15, 17, 19, 20]}
G = nx.Graph(d)
edges = list(G.edges)
print(edges)

输出

[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 10), (1, 12), (8, 9), (14, 15), (14, 17), (14, 19), (14, 20)]

替代使用convert.from_dict_of_lists

import networkx as nx

d = {1: [2, 3, 4, 5, 6, 7, 8, 10, 12], 8: [9], 14: [15, 17, 19, 20]}
G = nx.convert.from_dict_of_lists(d)
edges = list(G.edges)
print(edges)

输出

[(1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 10), (1, 12), (8, 9), (14, 15), (14, 17), (14, 19), (14, 20)]