python - 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!)
解决方案
由于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.
推荐阅读
- java - 为什么Maven找不到org.json JPMS自动模块?
- python - 使用 BeautifulSoup 和 Requests 从 HTML 中获取文本
- javascript - vue-instantsearch 在我的 VueJS 3.0 项目中不起作用
- javascript - 当我创建一张新卡并将其添加到它的父级时,图像不会加载 innerHTML
- kubernetes - 具有不同 cpu 核心数的节点上的 kubernetes pod 资源 cpu
- php - 如何从此字符串中删除“”和空格
- python - 如何从目录中的所有文件中读取行?
- html - 使用图像调整容器大小以适应另一个容器的大小
- reactjs - 使用使用 nwb 创建的模块时,CSS 模块不会在 NextJS 中导入
- python - 我怎样才能解决ValueError:字段'cid'期望一个数字但得到''。?