python - 如何修复“RuntimeError:迭代期间字典更改大小”,同时编辑一些图形数据
问题描述
Objectif:我有一个图,对于每个具有二度的节点,我想删除该节点并在该节点的邻居之间添加一条边(权重 = a*b/a+b,其中 a 和 b 是有问题的节点的相邻边)。我想在每次图形更改时执行这些操作,最终得到一个没有任何节点的图形 dgree 2 。这是我附上的代码。PS:我对python(3.4.0),NetworkX 2.2非常陌生(任何其他给出类似结果的建议表示赞赏)
import networkx as nx
import matplotlib.pyplot as plt
G=nx.MultiGraph()
G.add_nodes_from([1,2,3,4,5,6,7])
G.add_edges_from([(1,2),(1,3),(2,4),(2,5),(3,6),(6,7)])
for u, v, d in G.edges(data=True):
d['weight'] = 1
def fun(G) :
L= G.degree() # L=list of all nodes of a random graph G ,and their nodes [(node, degree),(node,degree)...]
for x in L :
if x[1] == 2 : #if a certain node in L has a degree 2
adja=G.edges(x[0],data=True) #adjacent edges to the node of degree 2
weights = [d['weight'] for u,v,weight in adja] #weights=list of weights of the adjacent edges to the node x[0](the one having degree 2)
numerator=weights[0]*weights[1]
denominator=sum(weights)
var=numerator/denominator #var is the weight i would like to assign to my new edge created,it is computed like : a*b /(a+b) with a and b are weights of the adjacent edges to the node in question
tmp=list(G.neighbors(x[0])) #tmp = list of neighbors of the node to remove(neighbors in term of nodes)
G.remove_node(x[0]) #remove the node of degree 2
G.add_edge(tmp[0],tmp[1],weight=var) #add an edge between the neighbors of the node of degree 2
nx.draw(G,with_labels=True)
plt.show()
print(fun(G))
解决方案
推荐阅读
- javascript - React/Firebase 用户注册承诺 - 无法在未安装的组件上调用 setState
- blueprism - 错误 - 突出显示结果 - 未找到匹配的窗口
- arduino - 如何通过 Arduino Mega 从 ESP 12S 获得 AT 响应?
- c++ - 如何对 unique_ptrs 列表进行排序?
- c - 运行 fork() 时子进程接管父进程
- python - 如何在python中存储到mysql之前评估数据大小
- python - 从变量python调用字典
- python - 如何标准化从 - inf 到 +inf 在 0,1 之间的数据,其中值 0 在标准化时始终等于 0.5?
- c# - 空引用 - 如何判断哪个变量是空引用?
- twitter-bootstrap - bootstrap (3.3.7) youtube 风格的图像轮播