簡體   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