首页 > 解决方案 > Networkx:将所有节点最短路径长度的总和作为一个聚合值

问题描述

我是使用 NetworkX 的初学者,我正在尝试找到一种方法,总结一个节点到图的其他节点的所有最短路径值作为一个聚合值,例如,节点B 的长度是6 如代码的波纹管结果。我得到了图中所有节点对之间的最短路径,但我需要帮助将每个节点的长度添加为一个值,如上所述。任何帮助将非常感激。下面是计算最短路径长度的代码。我编辑了问题,以便将node_density值传递给单个节点,如下面的代码所示。

>>> import networkx as nx
>>> G = nx.Graph()
>>> G.add_nodes_from(["A", "B", "C", "D", "E"])
>>> G.add_edges_from([("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")])
>>> sp = nx.all_pairs_shortest_path(G)
>>> sp["A"]["E"]
['A', 'B', 'C', 'D', 'E']
>>> spl = nx.all_pairs_shortest_path_length(G)
>>> spl["A"]["E"]
4
>>> dc = 1
>>> for node1 in spl:
...   for node2 in spl[node1]:
...     print("Length between", node1, "and", node2, "is", spl[node1][node2])
...     node_density = spl[node1][node2] - dc
        if(node_density <= 0):
            node_density = 1
        else:
            node_density = 0
Length between B and B is 0
Length between B and A is 1
Length between B and E is 3
Length between B and C is 1
Length between B and D is 2
Length between A and B is 1
... (and so on!)

标签: pythonnetworkxgraph-theory

解决方案


由于spl是 dicts 的 dicts 将每个节点的长度保存到每个其他节点,您可以循环通过外部 dict 并将长度值求和到每个其他节点。

import networkx as nx
G = nx.Graph()
G.add_nodes_from(["A", "B", "C", "D", "E"])
G.add_edges_from([("A", "B"), ("B", "C"), ("C", "D"), ("D", "E")])
sp = dict(nx.all_pairs_shortest_path(G))
sp["A"]["E"]
# ['A', 'B', 'C', 'D', 'E']
spl = dict(nx.all_pairs_shortest_path_length(G))
# spl["A"]["E"]


# sum the lengths to individual nodes
new_dict = {node1: sum([length for length in spl[node1].values()]) for node1 in spl.keys()}
# print the lengths
for node,length in new_dict.items():
    print('The sum of lengths from node {} to all other nodes is {}.'.format(node,length))

#The sum of lengths from node A to all other nodes is 10.
#The sum of lengths from node B to all other nodes is 7.
#The sum of lengths from node C to all other nodes is 6.
#The sum of lengths from node D to all other nodes is 7.
#The sum of lengths from node E to all other nodes is 10.

推荐阅读