Networkx: Use common function for edge weight calculation

Suppose I have a function euc_2d(graph, n1, n2) that calculates the euclidean distance between two nodes of the same graph. Each nodes has a given pos=(x,y) which is assigned on graph creation.

NetworkX provides a function to get the total weight of all edges of a graph namely graph.size(weight='weight') . The problem with this method is that it assumes that whenever I add an edge I should explicitly assign the appropriate edge weight like graph.add_edge(u,v,weight=?) using a lambda function for example.

However this is very inconvenient (and verbose) since I keep adding and removing edges in the graph all the time.

So, is there a pythonic way I can tell NetworkX to transparently use the euc_2d() whenever I ask the total weight of the graph?


Neither graph.size nor graph.add_edge uses a function to evaluate the weight, they just store values with a given key. To make it easier to work with, just define a function to add an edge with the appropriate weight:

def add_euc2d_edge(graph, u, v):
    graph.add_edge(u, v, weight=euc_2d(graph, u, v))
链接地址: http://www.djcxy.com/p/29220.html

上一篇: 最小化双向图中的交叉点数量

下一篇: Networkx:使用通用功能进行边缘权重计算