在这段代码中,我试图从字典中删除列表中的7个字符或更少字符的值(同义词)。由于某种原因,我的代码仅部分删除了7个字符或更少字符的值。另外,请不要删除任何功能或使用导入和设置来解决和保持当前代码尽可能完整。

我当前的输出:

{'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}



所需的输出:

{'show' : ['demonstrate', 'indicate', 'point to'],
'slow' : ['leisurely', 'unhurried'],
'dangerous' : ['hazardous', 'perilous', 'uncertain']}


word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
             'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
             'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        for item in value:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()

最佳答案

您正在修改for item in value:时要迭代的列表。
相反,您需要在value[:]上进行迭代,该方法返回数组的副本

word_dict = {'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        #Iterate on copy of value
        for item in value[:]:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()



输出将是

{
'show': ['point to', 'indicate', 'demonstrate'],
'slow': ['unhurried', 'leisurely'],
 'dangerous': ['perilous', 'hazardous', 'uncertain']
}


另一个选择是创建一个新列表,将带有len>7的单词添加到列表中,并将该列表分配给字典的键

 word_dict = {'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)


def remove_word(word_dict):
    for key, value in word_dict.items():

        #List of holding words with len more that 7
        li = []
        for item in value:
            #Add words with len more than 7 to the list
            if len(item) > 7:
                li.append(item)
        #Assign the list to the key
        word_dict[key] = li
    return word_dict

main()

10-01 01:56
查看更多