微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

执行部分列表项匹配到另一个与捕获

如何解决执行部分列表项匹配到另一个与捕获

我有两个列表:

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']
,

您必须在条件表达式中使用单独的列表推导式。在您的理解中,您为每个不在 j 中的 for i in list_1 添加了一个 i j,这就是您得到重复的原因。

output = [j for j in list_2 if all([i not in j for i in list_1])]
,

您想检查短语中是否出现任何单词,因此 any 是要走的路。在我看来,这比使用 all 和否定检查更具可读性。

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

result = [phrase for phrase in phrases if not any(word in phrase for word in words)]
print(result)

你得到 ['puppies are best']


解决方案大致相当于:

result = []
for phrase in phrases:
    contains_any_word = False
    for word in words:
        if word in phrase:
            contains_any_word = True
            break
    if not contains_any_word:
        result.append(phrase)
,

如何使用 set 交叉口?

list_1 = ['world','rock']
list_2 = ['the world is big','you rock the world']

words = set(list_1)
output = [i for i in list_2 if not words & set(i.split())]
print(output)

输出:

['puppies are best']

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?