如何检查列表中的任何项是否出现在另一个列表中?

2024-06-01 00:56:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有以下列表:

listA = ["A","Bea","C"]

还有另一张单子

^{pr2}$

检查listA中的任何项是否出现在listB或stringB中的最佳方法是什么,如果是,则停止?我通常使用for循环遍历listA中的每一项来完成这项工作,但是在语法上有没有更好的方法呢?在

for item in listA:
    if item in listB:
        break;

Tags: 方法in列表forif语法item单子
2条回答

您可以在这里使用anyany将短路并在找到第一个匹配项时停止。在

>>> listA = ["A","B","C"]
>>> listB = ["B","D","E"]
>>> stringB = "There is A loud sound over there"
>>> lis = stringB.split()
>>> any(item in listA or item in lis for item in listA) 
True

如果listB很大,或者{}返回的列表很大,则应首先将其转换为sets,以提高复杂性:

^{pr2}$

如果要在该字符串中搜索多个单词,请使用regex

>>> import re
>>> listA = ["A","B","C"]
>>> listB = ["B","D","E"]
>>> stringB = "There is A loud sound over there"
>>> any(item in listA or re.search(r'\b{}\b'.format(item),stringB)
                                                              for item in listA) 

要查找两个列表的重叠,可以执行以下操作:

len(set(listA).intersection(listB)) > 0

if语句中,您只需执行以下操作:

^{pr2}$

但是,如果listA中的任何项超过一个字母,则set方法不适用于查找stringB中的项,因此最好的替代方法是:

any(e in stringB for e in listA)

相关问题 更多 >