python - 使用 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]
解决方案
您应该尽可能考虑为变量提供有意义的名称,这有助于您编写代码
你想要的是
- 遍历句子
- 每次检查其中没有来自
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']
推荐阅读
- matlab - 从不同表中的变量值构建 Matlab 表时出错
- python - 如何在 android(buildozer) 上使用 kivy 在 python 中创建目录 (mkdir)?
- javascript - 在 React Native 中找不到变量
- sql - SQL 多对多过滤掉项目而不是包含
- php - Guzzle:“标头值必须是标量”
- amazon-s3 - 检查 Databricks 笔记本中是否存在 S3 目录
- php - 如何在 HTML 中编写 PHP 代码,最后一个在 PHP 中?
- angular - 参数“res”隐式具有“any”类型
- sql - (错误) ORA-02270: 此列列表没有匹配的唯一键或主键
- java - 在 Java 中解析制表符分隔的文本文件时出现错误 ArrayIndexOutOfBoundsException