您可以any
在此处使用:any
将短路并在找到的第一个匹配项处停止。
>>> 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
first 以提高复杂性:
>>> 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)