ort*_*ng2 5 python arrays for-loop list
我有一个字符串列表,我想搜索一个单词组合.如果组合不存在,则删除列表.是否有一个python列表理解可行?
word_list = ["Dogs love ice cream", "Cats love balls", "Ice cream", "ice cream is good with pizza", "cats hate ice cream"]
keep_words = ["Dogs", "Cats"] 
Delete_word = ["ice cream"]
Run Code Online (Sandbox Code Playgroud)
删除里面有冰淇淋的单词,但如果句子中有狗或猫,请保留它.
Desired_output = ["Dogs love ice cream", "Cats love balls", "cats hate ice cream"] 
Run Code Online (Sandbox Code Playgroud)
尝试此代码也试过AND和OR,但无法正确组合.
output_list = [x for x in  word_list if "ice cream" not in x]
Run Code Online (Sandbox Code Playgroud)
    这是一个列表理解解决方案:
[x for x in word_list if any(kw.lower() in x.lower() for kw in keep_words) 
 or all(dw.lower() not in x.lower() for dw in Delete_word)]
# ['Dogs love ice cream', 'Cats love balls', 'cats hate ice cream']
Run Code Online (Sandbox Code Playgroud)
这还为删除单词列表中的多个单词增加了灵活性.
说明
如果以下任何一项出现,请对列表进行迭代并保留该单词True:
我从你的例子中假设你希望这个不区分大小写,所以要对这些单词的低级版本进行所有比较.
作为一个优化的方法,你可以把你keep_word和delete_words集合以及使用itertools.filterfalse()过滤列表出来:
In [48]: def key(x):
             words = x.lower().split()
             return keep_words.isdisjoint(words) or not delete_words.isdisjoint(words)
   ....: 
In [49]: keep_words = {"dogs", "cats"}
In [51]: delete_words = {"ice cream"}
In [52]: list(filterfalse(key ,word_list))
Out[52]: ['Dogs love ice cream', 'Cats love balls', 'cats hate ice cream']
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           111 次  |  
        
|   最近记录:  |