我需要从给定的边列表中构建图形,如下所示:
Edges = ["cc-gc","cc-da","ee-cd","ee-bg","de-bg"]
从上面的边列表中,我如何获得这样的图形:
graph = { "cc" : ["gc","da"],
"gc" : ["cc"],
"da": ["cc"],
"ee": ["cd", "bg"],
"cd": ["ee"],
"de": ["bg"],
"bg": ["de", "ee"]
}
使用networkX
,我们可以通过拆分列表中的字符串来构建图,然后查找所有节点的nx.neighbors
:
nx.neighbors
import networkx as nx
G = nx.from_edgelist([s.split('-') for s in Edges])
graph = dict()
for node in G.nodes():
graph[node] = list(nx.neighbors(G, node))
使用networkx
,我们可以通过分散列表中的字符串并找到所有节点的nx.neighbors
来构建图形:
nx.neighbors
import networkx as nx
G = nx.from_edgelist([s.split('-') for s in Edges])
graph = dict()
for node in G.nodes():
graph[node] = list(nx.neighbors(G, node))