Networkx:使用通用功能进行边缘权重计算 [英] Networkx: Use common function for edge weight calculation
问题描述
euc_2d(graph,n1,n2)
来计算同一图形的两个节点之间的欧式距离。每个节点都有一个给定的 pos =(x,y)
,它在创建图表时分配给它。 NetworkX提供函数来获得图的所有边的总权重,即 graph.size(weight ='weight')
。这个方法的问题是,它假定每当我添加一个边时,我都应该明确地使用 graph.add_edge(u,v,weight =?)
来使用相应的边权重例如一个lambda函数。
然而,这是非常不方便的(并且是冗长的),因为我始终在图表中添加和删除边缘。
那么,当我问图的总权重时,是否可以通过pythonic的方式告诉NetworkX透明地使用 euc_2d()
.add_edge 使用函数来评估权重,它们只是使用给定的键存储值。为了使它更易于使用,只需定义一个函数来添加具有适当权重的边:
def add_euc2d_edge(graph, u,v):
graph.add_edge(u,v,weight = euc_2d(graph,u,v))
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))
这篇关于Networkx:使用通用功能进行边缘权重计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!