gpt4 book ai didi

python - 如何通过指定规则改变边缘的权重?

转载 作者:IT老高 更新时间:2023-10-28 21:18:46 25 4
gpt4 key购买 nike

我有一个加权图:

F=nx.path_graph(10)
G=nx.Graph()
for (u, v) in F.edges():
G.add_edge(u,v,weight=1)

获取节点列表:

[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]

我想通过这条规则改变每条边的权重:

删除一个节点,比如节点5,很明显,边(4, 5)(5, 6)会被删除,每个节点的权重边缘将转向:

{# these edges are nearby the deleted edge (4, 5) and (5, 6)

(3,4):'weight'=1.1,

(6,7):'weight'=1.1,

#these edges are nearby the edges above mentioned

(2,3):'weight'=1.2,

(7,8):'weight'=1.2,

#these edges are nearby the edges above mentioned

(1,2):'weight'=1.3,

(8,9):'weight'=1.3,

# this edge is nearby (1,2)

(0,1):'weight'=1.4}

这个算法怎么写?

path_graph 只是一个例子。我需要一个适合任何图形类型的程序。此外,程序需要是可迭代的,这意味着我每次可以从原始图中删除一个节点。

最佳答案

您可以通过 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})]

关于python - 如何通过指定规则改变边缘的权重?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3965360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com