Python “如何修复”;运行时错误:字典在迭代过程中更改了大小,在编辑一些图形数据时

Python “如何修复”;运行时错误:字典在迭代过程中更改了大小,在编辑一些图形数据时,python,python-3.x,graph,networkx,graph-theory,Python,Python 3.x,Graph,Networkx,Graph Theory,目标F:我有一个图,对于每一个具有二度的节点,我想删除该节点,并在该节点的相邻节点之间添加一条边(权重=a*b/a+b,其中a和b是相关节点相邻边的权重)。我想在每次图改变时执行这些操作,最终生成一个没有任何节点的图,该图具有dgree 2。这是我的代码附件。PS:我对python(3.4.0)和Networkx2.2非常陌生 (对于提供类似结果的任何其他建议,我们表示感谢) @PatrickArtner,谢谢你的快速回复,我是python新手,我不知道如何“将要修改的键存储在列表中,迭代到结尾

目标F:我有一个图,对于每一个具有二度的节点,我想删除该节点,并在该节点的相邻节点之间添加一条边(权重=a*b/a+b,其中a和b是相关节点相邻边的权重)。我想在每次图改变时执行这些操作,最终生成一个没有任何节点的图,该图具有dgree 2。这是我的代码附件。PS:我对python(3.4.0)和Networkx2.2非常陌生 (对于提供类似结果的任何其他建议,我们表示感谢)


@PatrickArtner,谢谢你的快速回复,我是python新手,我不知道如何“将要修改的键存储在列表中,迭代到结尾,然后修改dict”。在我的例子中,我附上了完整的代码,以及每个指令的解释。您可以通过使用一个L的副本迭代来修复即时错误:
对于L[:]中的x:
-但我想我看起来不像你想的那样-我不熟悉
networkx
-我把它作为标签添加了,希望有人能来:)对不起。我真的很感谢你的帮助,谢谢you@PatrickArtner我想说,你的提示帮助我解决了这个问题,现在它起作用了,非常感谢。下面是我在前面的代码中添加的内容(对于可能面临相同问题的其他用户):L=list(L1)表示L中的x
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))