如何从python中的给定边列表创建图字典

问题描述 投票:2回答:2

我需要从给定的边列表中构建图形,如下所示:

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"]
    }
python graph edges
2个回答
2
投票

使用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))

0
投票

使用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))
© www.soinside.com 2019 - 2024. All rights reserved.