簡體   English   中英

如何通過讀取.txt文件為每個鍵創建包含多個“列表”的Python字典?

[英]How to create Python dictionary with multiple 'lists' for each key by reading from .txt file?

我有一個大文本文件,看起來像:

1   27  21  22
1   151 24  26
1   48  24  31
2   14  6   8
2   98  13  16
.
.
.

我想用它創建一個字典。 每個列表的第一個數字應該是字典中的鍵,應該采用以下格式:

{1: [(27,21,22),(151,24,26),(48,24,31)],
 2: [(14,6,8),(98,13,16)]}

我有以下代碼(總點數是文本文件第一列中的最大數字(即字典中的最大鍵)):

from collections import defaultdict

info = defaultdict(list)
filetxt = 'file.txt'
i = 1

with open(filetxt, 'r') as file:
    for i in range(1, num_cities + 1):
        info[i] = 0
    for line in file:
        splitLine = line.split()
        if info[int(splitLine[0])] == 0:
            info[int(splitLine[0])] = ([",".join(splitLine[1:])])
        else:
            info[int(splitLine[0])].append((",".join(splitLine[1:])))

哪個輸出

{1: ['27,21,22','151,24,26','48,24,31'],
 2: ['14,6,8','98,13,16']}

我想要這個字典的原因是因為我想在給定鍵的字典的每個“內部列表”中運行for循環:

for first, second, third, in dictionary:
   ....

我不能用我當前的代碼執行此操作,因為字典的格式略有不同(它在上面的for循環中需要3個值,但是接收的值超過3個),但它可以使用第一個字典格式。

任何人都可以建議解決這個問題嗎?

result = {}
with open(filetxt, 'r') as f:
    for line in f:
        # split the read line based on whitespace
        idx, c1, c2, c3 = line.split()

        # setdefault will set default value, if the key doesn't exist and
        # return the value corresponding to the key. In this case, it returns a list and
        # you append all the three values as a tuple to it
        result.setdefault(idx, []).append((int(c1), int(c2), int(c3)))

編輯:由於您希望鍵也是一個整數,您可以將int函數map到拆分值,如下所示

        idx, c1, c2, c3 = map(int, line.split())
        result.setdefault(idx, []).append((c1, c2, c3))

您正在將值轉換回逗號分隔的字符串,這些字符串不能用於數據中for first, second, third in data - 所以只需將它們保留為列表splitLine[1:] (或轉換為tuple )。
您不需要使用defaultdict初始化for循環。 您也不需要使用defaultdict進行條件檢查。

你的代碼沒有多余的代碼:

with open(filetxt, 'r') as file:
    for line in file:
       splitLine = line.split()
       info[int(splitLine[0])].append(splitLine[1:])

一個細微的差別是如果你想在int上運行我會在前面進行轉換:

with open(filetxt, 'r') as file:
    for line in file:
       splitLine = list(map(int, line.split()))   # list wrapper for Py3
       info[splitLine[0]].append(splitLine[1:])

實際上在Py3中,我會這樣做:

       idx, *cs = map(int, line.split())
       info[idx].append(cs)

暫無
暫無

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

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