首页 > 解决方案 > 使用 catch 执行部分列表项匹配到另一个列表项

问题描述

我有两个清单:

list_1 = ['world', 'abc', 'bcd', 'ghy', 'car', 'hell', 'rock']
list_2 = ['the world is big', 'i want a car', 'puppies are best', 'you rock the world']

我想检查 list_1 的单词是否以任何形状或形式存在于 list_2 中,然后简单地从 list_2 中删除整个句子,最后打印 list_2

例如:

the word 'world' from list_1 should take out the sentence 'the world is big' from list_2
the word 'car' from list_2 should take out the sentence 'i want a car'

我试过使用这样的列表理解,但遗憾的是它重复了

output = [j for i in list_1 for j in list_2 if i not in j]

标签: pythonlistlist-comprehension

解决方案


您应该尽可能考虑为变量提供有意义的名称,这有助于您编写代码

你想要的是

  • 遍历句子
  • 每次检查其中没有来自list_1的单词
output = [sentence for sentence in list_2
          if all(word not in sentence for word in list_1)]

print(output)  # ['puppies are best']

推荐阅读