繁体   English   中英

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

[英]How to check if any item in a list occurs in another list?

如果我有以下列表:

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;

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

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

if语句中,您可以简单地执行:

if set(listA).intersection(listB):

但是,如果listA中的任何项长于一个字母,则set方法将无法用于查找stringB项,因此最佳替代方法是:

any(e in stringB for e in listA)

你可以在这里使用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很大或者从stringB.split()返回的列表很大,那么你应该首先将它们转换为sets以提高复杂性:

>>> 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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM