繁体   English   中英

Python,RuntimeError:字典在迭代过程中更改了大小

[英]Python, RuntimeError: dictionary changed size during iteration

我正在尝试从给定的网络中创建某种残差网络,为此,我首先创建了图形中不存在的反向边,但是我不断收到消息

RuntimeError: dictionary changed size during iteration

首先,我显然要遍历循环中正在修改的对象:

def Gf(Graph):    #residual graph
 for u in Graph:
    for v in Graph[u]:
        if u in Graph[v]: 
            pass
        else:
            Graph[v][u]=0 #create the edge with capacity 0
 return Graph

图Graph是形式的对象(我是python的新手,所以我不知道这是否是最好的方法)

defaultdict(lambda:defaultdict(lambda:0))

值Graph [u] [v]设置为边u,v的容量。

所以我创建了Graph的副本,并尝试遍历该对象

def Gf(Graph):    #residual graph
 Graph_Copy=Graph.copy()
 for u in Graph_Copy:
    for v in Graph_Copy[u]:
        if u in Graph_Copy[v]: 
            pass
        else:
            Graph[v][u]=0 
 return Graph

但这没有用。 我尝试了其他方法(创建深度复制;创建空对象Graph_Copy,遍历Graph,然后将足够的值设置为Graph_Copy),但到目前为止还没有运气。 我做错了什么?

老实说,我不知道是什么导致了您的异常。 但是,我所知道的是,使用嵌套字典来表示图是一个坏主意。 正如您所发现的,它们很难遍历,并且开销更大。 相反,您应该使用嵌套列表。

如果我正确理解您当前的数据结构,则可以表示如下:

graph = {
    u0: {v0: 0, v1: 0, ... },
    u1: {v0: 0, v1: 0, ... },
    ...
}  # the curly brackets denote dictionaries

更好的表示是:

graph = [
    [0, 0, 0, ...],
    [0, 0, 0, ...],
    ...
]  # the brackets denote lists

这是编码图形的距离矩阵( http://en.wikipedia.org/wiki/Distance_matrix )表示形式的默认方法。 如果您使用其他语言(如C / C ++)进行编码,则这等效于二维数组。

假设uv是图形顶点的标签,则可以将它们表示为数值,即第1个节点为0,第2个节点为1,依此类推。 访问边缘uv的值就像执行graph[u][v]一样简单。

现在,假设您已更改代码,以使具有N个顶点的图形G表示为大小为NxN的嵌套列表/ 2D数组,则可以按以下方式重写函数:

def gf(g):  # python style guideline recommends lower case variable & function names
    vertices_count = len(g)  # get the size of the original graph
    gf = []   # initialize the new redidual graph
    for u in range(vertices_count):
        gf.append([0]*vertices_count)  # initialize the edges
        for v in range(vertices_count):
            if g[u][v] > 0:
                # do something here if the value of edge u-v is more than zero, e.g. gf[u][v] = some formula
            else:
                # do something here if the value of edge u-v is zero,, e.g. gf[u][v] = 0
    return gf

错误是因为您使用的是defaultdict 因此,看起来像只读操作(例如Graph[u] )的内容实际上可以添加键并更改字典大小。

编辑:删除了使用copydeepcopy建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM