如何将边的权重传递给 Networkx 函数的权重参数

How to Pass Weights of Edges to the Weight Argument of a Networkx Function

具体的功能是edge_betweeness_centrality。我试图获得边缘的其中一张图是加权图。我的问题是我如何能够为函数提供图中每条边的权重?我几乎总是处理未加权的图,所以通常我总是可以将权重参数保留为默认值 none,但这是我第一次处理加权图。我想这也适用于在使用加权图时将图的权重作为参数的任何函数。

在networkx中传递有权重的边可以用这种方式完成。

import networkx as nx

# Creating the graph
G = nx.Graph()

#Creating the list of weighted edges
elist = [('a','b', 5.0), ('b','c',3.0), ('c','d',7.3)]
# Adding them to the graph
G.add_weighted_edges_from(elist)

#Calling edge_betweenness_centrality
nx.edge_betweenness_centrality(G, weight='weight')

输出:

{('a', 'b'): 0.5, ('b', 'c'): 0.6666666666666666, ('c', 'd'): 0.5}

来自documentation

weight: (None or string, optional (default=None)) – If None, all edge weights are considered equal. Otherwise holds the name of the edge attribute used as weight.

此链接将在以后的 documentation 示例 中为您提供帮助。此示例带有 betweenness_centrality,但也可以应用于您要求的功能。通常,对于 networkx,您可以通过这种方式传递加权边列表,有关更多信息,请参阅 文档.