从列表中删除不包含特定词的字符串?
比如像这样(虽然这个代码不能运行):
list1 = ['hello, how are you?', 'well, who are you', 'what do you want']
desiredwords = ['hello', 'well']
list2 = [x for x in list1 if any(word in list1 for word in desiredwords) in x]
print list2
['hello, how are you?', 'well, who are you'] #Desired output
有没有人知道怎么做到这一点?
1 个回答
3
你在错误的生成器表达式上调用了 any
。你应该这样做:
list2 = [x for x in list1 if any(word in x for word in desiredwords)]
这里的区别在于,你的问题中是在判断你想要的单词列表中的任何一个单词是否在 list1
中(它们并不在),然后再测试 False
(你调用 any
的结果)是否在你正在测试的 list
的元素中。这显然是行不通的。
而我的 any
版本是检查你想要的单词列表中的单词是否和正在考虑的元素匹配,利用 any
的输出结果来过滤列表。
需要注意的是,字符串中的 in
是进行子串匹配的——这种方法会把 "oilwell" 视为匹配 "well"。如果你想要这样的效果,那没问题。如果不想,那就会变得更复杂。