python - 如何从字典中删除指定长度字符以下的值?

标签 python list dictionary for-loop key-value-store

在此代码中,我试图从字典中删除列表中不超过 7 个字符的值(同义词)。出于某种原因,我的代码只是部分删除了 7 个或更少字符的值。另外,请不要删除任何函数或使用 imports 和 sets 来解决并尽可能保持当前代码的完整性。

我当前的输出:

{'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()

关于python - 如何从字典中删除指定长度字符以下的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56311192/

相关文章:

r - 如何将列表添加到 R 中的数据框?

C++ 当使用 insert() 将堆对象插入 std::map 并且存在另一个对象时,谁删除了新对象?

python - Python中是否有相当于//运算符的上限?

python - 使用 Flask WTForms validate_on_submit 总是返回 false

Python 创建一个包含打乱元素并按对象引用的子列表

python - 如何在 Python 3 中正确包装字典?

javascript - NodeJS 没有序列化 ES6 Map

python - Tensorflow:运算中的基本 Python 计算

python - Python 中的截断与下限划分

c++ - std::list 的新位置