I have a weighted graph:
我有一个加权图
F=nx.path_graph(10)
G=nx.Graph()
for (u, v) in F.edges():
G.add_edge(u,v,weight=1)
get the nodes list:
得到节点列表:
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
I want to change each edge's weight by this rule:
我想通过以下规则来改变每条边的重量:
remove one node, such as node 5, clearly, edge (4, 5) and (5, 6) will be delete, and the weight of each edge will turn to:
删除一个节点,如节点5,显然,删除边(4,5)和(5,6),各边的权值变为:
{# these edges are nearby the deleted edge (4, 5) and (5, 6)
{#这些边在被删除的边(4,5)和(5,6)附近
(3,4):'weight'=1.1,
(3、4):“重量”= 1.1,
(6,7):'weight'=1.1,
(6、7):“重量”= 1.1,
#these edges are nearby the edges above mentioned
#这些边在上面提到的边附近
(2,3):'weight'=1.2,
(2、3):“重量”= 1.2,
(7,8):'weight'=1.2,
(7、8):“重量”= 1.2,
#these edges are nearby the edges above mentioned
#这些边在上面提到的边附近
(1,2):'weight'=1.3,
(1、2):“重量”= 1.3,
(8,9):'weight'=1.3,
(8、9):“重量”= 1.3,
# this edge is nearby (1,2)
#这条边在(1,2)附近
(0,1):'weight'=1.4}
(0,1):“重量”= 1.4 }
How to write this algorithm?
如何编写这个算法?
PS: path_graph is just an example. I need a program suit any graph type. Furthermore, the program need to be iterable, it means I can remove one node from origin graph each time.
path_graph只是一个示例。我需要一个适合任何图形类型的程序。此外,程序需要是可迭代的,这意味着我可以每次从原点图中删除一个节点。
Regards
问候
1 个解决方案
#1
25
You can access the edge weight as G[u][v]['weight'] or by iterating over the edge data. So you can e.g.
您可以以G[u][v]['weight']的形式访问边缘权值,或者通过迭代边缘数据。所以你可以如。
In [1]: import networkx as nx
In [2]: G=nx.DiGraph()
In [3]: G.add_edge(1,2,weight=10)
In [4]: G.add_edge(2,3,weight=20)
In [5]: G[2][3]['weight']
Out[5]: 20
In [6]: G[2][3]['weight']=200
In [7]: G[2][3]['weight']
Out[7]: 200
In [8]: G.edges(data=True)
Out[8]: [(1, 2, {'weight': 10}), (2, 3, {'weight': 200})]
In [9]: for u,v,d in G.edges(data=True):
...: d['weight']+=7
...:
...:
In [10]: G.edges(data=True)
Out[10]: [(1, 2, {'weight': 17}), (2, 3, {'weight': 207})]
#1
25
You can access the edge weight as G[u][v]['weight'] or by iterating over the edge data. So you can e.g.
您可以以G[u][v]['weight']的形式访问边缘权值,或者通过迭代边缘数据。所以你可以如。
In [1]: import networkx as nx
In [2]: G=nx.DiGraph()
In [3]: G.add_edge(1,2,weight=10)
In [4]: G.add_edge(2,3,weight=20)
In [5]: G[2][3]['weight']
Out[5]: 20
In [6]: G[2][3]['weight']=200
In [7]: G[2][3]['weight']
Out[7]: 200
In [8]: G.edges(data=True)
Out[8]: [(1, 2, {'weight': 10}), (2, 3, {'weight': 200})]
In [9]: for u,v,d in G.edges(data=True):
...: d['weight']+=7
...:
...:
In [10]: G.edges(data=True)
Out[10]: [(1, 2, {'weight': 17}), (2, 3, {'weight': 207})]