根据 networkx (Python) 中的边权重排序的邻居边

Pra*_*tal 2 python graph networkx

我已经建立了一个基于 networkx 的图,其中边代表它们之间的距离。

  GraphLoc.G.add_edge(fnode_id, snode_id, score=score)
Run Code Online (Sandbox Code Playgroud)

score 是边权重。

我无法找到可以提供具有边缘和结果按权重排序的相邻节点的 API。

显然我也可以自己排序,但我不想要运行时计算。networkx 是否为此提供任何解决方案

Tim*_*ara 5

选择单个节点将返回其邻居。然后,您可以相当轻松地自己对边缘列表进行排序。首先,我们设置图形。

>>> G = nx.Graph()
>>> G.add_edge('a', 'b', score=3)
>>> G.add_edge('b', 'c', score=4)
>>> G.add_edge('a', 'c', score=1)
Run Code Online (Sandbox Code Playgroud)

如果我们想要a的邻居,我们只需直接访问该节点:

>>> G['a']
{'b': {'score': 3}, 'c': {'score': 1}}
Run Code Online (Sandbox Code Playgroud)

为了对这些结果进行排序,我们使用标准 Python 工具箱中的工具。.items()dictatuplesorted内置函数转换为对结果进行排序:

>>> sorted(G['a'].items(), key=lambda edge: edge[1]['score'])
[('c', {'score': 1}), ('b', {'score': 3})]
Run Code Online (Sandbox Code Playgroud)

如果您需要明确结果和原始节点之间的关系,可以很容易地将其包含在具有列表推导式的结果中:

>>> neighbors = sorted(G['a'].items(), key=lambda edge: edge[1]['score'])
>>> [('a', node) for node, _metadata in neighbors]
[('a', 'c'), ('a', 'b')] 
Run Code Online (Sandbox Code Playgroud)