[Python]检查列表中的任何字符串是否包含另一个列表中的任何字符串

时间:2020-04-25 15:30:02

标签: python string list substring

我正在为Google新闻编写脚本。

我获得了新闻标题列表,并希望检查标题是否包含列表中的所有关键字。

例如

newstitle =['Python is awesome', 'apple is tasty', 'Tom cruise has new movie']
tag = ['Python','Orange', 'android']

如果新闻标题中有标签中的任何关键字,我希望它返回True值。

我知道如何使用单个标签进行操作

any('Python' in x for x in newstitle)

但是如何使用多个关键字呢? if循环是可行的,但似乎很愚蠢。

请帮助。预先感谢。

2 个答案:

答案 0 :(得分:4)

以下代码应达到要求:

any(t in x for x in newstitle for t in tag)

来自docs

列表推导由包含表达式的方括号组成 后跟一个for子句,然后是零个或多个for或if子句。的 结果将是评估表达式中 紧随其后的for和if子句的上下文。

答案 1 :(得分:0)

对于列表中的每个新闻标题,遍历标签列表以获取新闻标题中的标签值。

newstitles = ['Python is awesome', 'apple is tasty', 'Tom cruise has new movie']
tags = ['Python', 'Orange', 'android']

for newstitle in newstitles:
   for tag in tags:
      if newstitle.find(tag) != -1:
           #Do your operation...


       
相关问题