簡體   English   中英

如何創建n個詞典列表

[英]How to create a list of n dictionaries

我正在學習Python,為了實踐目的,我正在編寫一個腳本來讀取文件(包含一個簡單圖形格式的圖形 ),並在圖形上運行幾個圖形算法。

我想過將圖形存儲在n個字典的列表中,其中n是頂點的數量,頂點的所有邊都存儲在字典中。

我試過這個

edges = [{} for i in xrange(num_vertexes)]
for line in file:
    args = line.split(' ')
    vertex1 = int(args[0])
    vertex2 = int(args[1])
    label = int(args[2])
    edges[vertex1][vertex2] = label

但我在最后一行收到此錯誤:

IndexError:列表索引超出范圍

看起來vertex1可能大於num_vertexes 假設從0開始的python索引和格式的wiki上的示例從1開始,最后一行的頂點數可能比索引的長度高1(我當然需要查看文件才能確定) )。 所以在python情況下, lst[0]是第一個元素,而lst[n-1]是最后一個元素,其中頂點1是第一個元素, n是最后一個元素。

所以這里的修復是使用vertex1 = int(args[0])-1

問題出在您的數據的某處,添加一些驗證以確保您的代碼不會阻塞不良數據。 如果一行有非數字,少於三個數字,或者如果vertex1 >= len(edges) ,則代碼將失敗。

edges = [{} for i in xrange(num_vertexs)]
for line in file:
    args = line.split(' ')
    if len(args) >= 3:
        try:
            vertex1 = int(args[0])
            vertex2 = int(args[1])
            label = int(args[2])
            if vertex1 < len(edges):
                edges[vertex1][vertex2] = label
            else:
                # value for vertex1 is too large
                pass
        except ValueError:
            # you got some non-number data
            pass
    else:
        # you got a line with not enough data
        pass

如果需要,可以使用日志記錄替換任何這些pass語句(如果不打算使用它們,也可以刪除else兩個else塊)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM