簡體   English   中英

當鍵是字符串的第二個值時,如何將多個字符串列表附加到字典中的鍵?

[英]How can I append multiple lists of strings to a key in dictionary when the key is the second value of a string?

假設我有

data = [['Sea', 'Blue', 'Fish', 'Swim'], 
    ['Bored', 'Annoyed', 'Frustrated', 'Done'], 
    ['Keyboard', 'Blue', 'Desktop', 'Mouse']]

我需要具有返回的功能

{'Blue': [['Sea', 'Fish', 'Swim'], ['Keyboard', 'Desktop', 'Mouse']],    
    'Annoyed': [['Bored', 'Frustrated, 'Done']]}

我有這個功能

def func():
    b = dict()
    for element in data:
        for i in element:
                if i[1] in b:
                    b[i[1]].append(i[0], i[2], i[3])
                else:
                    b[i[1]] = (i[0], i[2], i[3])

但它返回:

builtins.IndexError: string index out of range

我希望這是有道理的,預先感謝您

您嵌套了太多的循環。 element已經是內部列表,例如['Sea', 'Blue', 'Fish', 'Swim'等。因此, i是字符串的字符。

還有其他一些問題,請參見下面的評論:

def func():
    b = dict()
    for element in data:
        if element[1] in b:
            b[element[1]].append([element[0], element[2], element[3]]) # append takes one argument
        else:
            b[element[1]] = [[element[0], element[2], element[3]]]  # list, not tuple
    return b  

暫無
暫無

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

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