[英]Dictionary containing all nodes and edges from graph
I need to build a graph from a given list of edges like this:我需要从给定的边列表中构建一个图,如下所示:
Edges = ["cc-gc","cc-da","ee-cd","ee-bg","de-bg"]
from list of edges above, how do I get the graph like this:从上面的边列表中,我如何得到这样的图表:
graph = { "cc" : ["gc","da"],
"gc" : ["cc"],
"da": ["cc"],
"ee": ["cd", "bg"],
"cd": ["ee"],
"de": ["bg"],
"bg": ["de", "ee"]
}
Using networkX
we can build a graph by splitting the strings in the list and using nx.from_edgelist
, and look for the nx.neighbors
of each node:使用networkX
,我们可以通过拆分列表中的字符串并使用nx.from_edgelist
来构建图,并查找每个节点的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))
print(graph)
{'cc': ['gc', 'da'],
'gc': ['cc'],
'da': ['cc'],
'ee': ['cd', 'bg'],
'cd': ['ee'],
'bg': ['ee', 'de'],
'de': ['bg']}
Use networkx.convert.to_dict_of_lists :使用networkx.convert.to_dict_of_lists :
import networkx as nx
edges = ["cc-gc", "cc-da", "ee-cd", "ee-bg", "de-bg"]
G = nx.from_edgelist([s.split('-') for s in edges])
print(nx.convert.to_dict_of_lists(G))
Output Output
{'bg': ['ee', 'de'],
'cc': ['gc', 'da'],
'cd': ['ee'],
'da': ['cc'],
'de': ['bg'],
'ee': ['cd', 'bg'],
'gc': ['cc']}
If the format is node1-node2
for all list elements a simple for loop does the trick如果所有列表元素的格式都是node1-node2
,那么简单的 for 循环就可以了
graph = {}
for edge in edges:
node1, node2 = edge.split('-')
if node1 in graph.keys():
graph[node1] += [node2]
else:
graph[node1] = [node2]
if node2 in graph.keys():
graph[node2] += [node1]
else:
graph[node2] = [node1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.