Skip to main content
 首页 » 编程设计

python之使用单词列表删除字典中的值python

2025年05月04日1052php

假设我有一个单词列表

 nottastyfruits = ['grape', 'orange', 'durian', 'pear'] 
 
 fruitGroup = {'001': ['grape','apple', 'jackfruit', 'orange', 'Longan'], 
               '002': ['apple', 'watermelon', 'pear']} 

我想遍历字典中的所有键并从 nottastyfruits 列表中删除单词。

我当前的代码是

finalfruits = {} 
for key, value in fruitGroup.items(): 
    fruits = [] 
    for fruit in value: 
        if fruit not in nottastyfruits: 
            fruits.append(fruit) 
    finalfruits[key] = (fruits) 

当你有大数据文本时,比如大文本预处理,这需要很长时间才能运行。有没有更高效、更快速的方法来做到这一点?

谢谢你的时间

请您参考如下方法:

通过使用字典理解使其平坦 将消除 for 循环的开销。

将 nottastyfruits 设为一个集合会减少查找时间:

nottastyfruits  = set(nottastyfruits) 
finalfruits = {k: [f for f in v if f not in nottastyfruits] for k, v in fruitGroup.items()}