簡體   English   中英

兩個清單之間的差異

[英]Difference between two list

我有以下文本文件:

text1 text2
# text2 text3 text4
# text5 text4 text6
text 3 text 4
# ....
...

我想有一個像下面這樣的數組列表

dict[function([text1, text2])] = [[text2, text3, text4], [text5, text4, text6]].

想法是打開文件,逐行讀取

dict = {}
inputfile = open("text.txt","r")
for line in inputfile:
    l=line.split()
if not line.startswith("#"):
#create a new key
else: 
dict[key] = l

但是,問題是,如果我轉到下一行,則無法分配其他元素。 你知道如何解決這個問題嗎?

“函數”只是我在其他地方定義的函數,它以字符串列表作為輸入。

您可以使用collections.defaultdict創建一個以list s為值的字典,您可以在其中附加項目。

from collections import defaultdict

my_dict = defaultdict(list)

with open('text.txt') as f:
    key = ''
    for line in f:
        if not line.startswith('#'):
            key = line
            # key = function(line.split())
            continue
        my_dict[key].append(line.strip('#').split())

print(my_dict)

輸出:

defaultdict(<class 'list'>,
            {'text1 text2\n': [['text2', 'text3', 'text4'],
                               ['text5', 'text4', 'text6']],
             'text3 text4\n': [['text21', 'text31', 'text41'],
                               ['text51', 'text41', 'text61']]})

只需將key = line line更改為您要將密鑰傳遞給的任何函數。

我的text.txt文件包含:

text1 text2
# text2 text3 text4
# text5 text4 text6
text3 text4
# text21 text31 text41
# text51 text41 text61

暫無
暫無

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

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