繁体   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