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

4
如果我有以下列表:
listA = ["A","Bea","C"]

并且还有另一个列表

listB = ["B","D","E"]
stringB = "There is A loud sound over there"

如何最好地检查listA中的任何项是否出现在listB或stringB中,如果是,则停止?我通常使用for循环迭代listA中的每个项来执行此操作,但从语法上讲是否有更好的方法?

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

对于字符串:您是要在字符串中查找字母,还是可以是多个字母? - David Robinson
可以是多个字母,是的。 - Rolando
stringB 和问题有关吗? - Hannele
是的,要能够找出列表A中的任何元素是否出现在字符串B中。 - Rolando
2个回答

9

要找出两个列表的交集,可以这样做:

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

if 语句中,你可以简单地这么做:
if set(listA).intersection(listB):

然而,如果listA中的任何项长度超过一个字母,则使用集合方法无法在stringB中查找项,因此最好的替代方法是:

any(e in stringB for e in listA)

你几乎永远不应该使用 len(x) > 0,因为这将在与 x 本身为真的情况下完全相同的情况下为真。根据 PEP8 的规定:“对于序列(字符串、列表、元组),使用空序列为假的事实。” - abarnert
相反地,是否有一种函数可以执行“交集”的相反操作,以查看仅存在于listA或listB中的项目数量? - Rolando
@Rolando:针对“仅属于A”的情况使用difference,或者针对“A或B中任意一个的独有元素”使用symmetric_difference。在交互式解释器中键入help(set)以查看集合可以执行的所有其他操作。 - abarnert
@Hannele:因为当你把一个字符串看作一个集合时,它是由单个字符组成的集合。set(listA).intersection(stringB)将查找与列表成员相等的单个字符字符串,因此set(['Ay', 'Bee']).intersection('AB')将为空。 - abarnert
哦,我误解了原帖问题的第二部分。谢谢澄清! - Hannele
显示剩余3条评论

1

您可以在此处使用任何任何将短路并在找到第一个匹配项时停止。

>>> 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很大或者从stringB.split()返回的列表很大,那么您应该首先将它们转换为set以提高复杂度:
>>> se1 =  set(listB)
>>> se2 = set(lis)
>>> any(item in se1 or item in se2 for item in listA)
True

如果您要在该字符串中搜索多个单词,则使用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) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接