在这段代码中,我试图从字典中删除列表中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()
创建一个新列表以筛选长度大于7的值,然后将其分配给相应的键。
简单地说,您可以这样修改代码:
这可以使用dict和list comp来完成:
我建议您使用它,而不是在迭代集合时尝试修改集合。它也比现有的其他选择更有效。你知道吗
当您执行
for item in value:
操作时,您正在修改正在迭代的相同列表。相反,您需要迭代
value[:]
,它返回数组的一个副本输出将是
另一种方法是创建一个新列表,将带有
len>7
的单词添加到列表中,并将列表分配给字典的键相关问题 更多 >
编程相关推荐