Reputation: 62704
If I have the following list:
listA = ["A","Bea","C"]
and another list
listB = ["B","D","E"]
stringB = "There is A loud sound over there"
What is the best way to check if any item in listA occurs in listB or stringB, if so then stop? I typically use for loop to iterate over each item in listA to do such a thing, but are there better ways syntactically?
for item in listA:
if item in listB:
break;
Upvotes: 4
Views: 2036
Reputation: 251146
You can use any
here: any
will short-circuit and will stop at the first match found.
>>> 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
If listB
is huge or the list returned from stringB.split()
is huge then you should convert them to sets
first to improve complexity:
>>> se1 = set(listB)
>>> se2 = set(lis)
>>> any(item in se1 or item in se2 for item in listA)
True
If you're searching for multiple words inside that string then use 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)
Upvotes: 1
Reputation: 78630
For finding the overlap of two lists, you can do:
len(set(listA).intersection(listB)) > 0
In if
statements you can simply do:
if set(listA).intersection(listB):
However, if any items in listA
are longer than one letter, the set approach won't work for finding items in stringB
, so the best alternative is:
any(e in stringB for e in listA)
Upvotes: 9