Reputation: 1
my code works like this if
listOne = ['hello','hi','bye']
listTwo = ['goodbye','bye']
for x in range(0,len(listOne))
listOne[x] in listTwo
>>>True
but consider this situation:
listOne = ['hello','hi','bye']
listTwo = ['goodbye','by']
for x in range(0,len(listOne):
listOne[x] in listTwo
>>>False
My need is to find if strings in listTwo are part of strings in listOne. However, I need to have each loop checking one item in listOne to all in listTwo on each instance
Thanks!!
Upvotes: 0
Views: 67
Reputation: 12669
One line solution :
print([item for item in listTwo for match in listOne if item in match])
output:
['by']
Detailed solution :
for item in listTwo:
for match in listOne:
if item in match:
print(item)
Upvotes: 0
Reputation: 1
It sounds like you want to match strings by partial match.
You can use list(string)
to break a string up into individual characters and compare them per character if that's what you want.
Example:
bye = list('bye')
goodbye = list('goodbye')
lettersMatched = 0
for x in range(len(bye)):
for y in range(len(goodbye)):
if bye[x] == goodbye[y]:
lettersMatched += 1
>>>lettersMatched
3
This allows you to set a requirement of minimum characters to match, don't use this code though, it's just for the concept. This would match anagrams as well. You'd probably be better off using regular expressions. You can make a regex with the smaller word as a pattern if you wanted to, for instance, match 'bye' with 'goodbye'.
Another use would be that you can use re.match('b?y?e?')
as a pattern to match 'bye' with 'by' but since it treats each character as optional it would also match with 'be'.
Hopefully these ideas are helpful to you! :)
Upvotes: 0
Reputation: 787
easiest way to solve
any( x for x in listTwo if x in listOne)
Upvotes: 0
Reputation: 2167
listOne = ['hello','hi','bye']
listTwo = ['goodbye','by', 'bye']
for x in listOne:
for y in listTwo:
if y in x:
print(x, y, True)
else:
print(x, y, False)
Output
hello goodbye False
hello by False
hello bye False
hi goodbye False
hi by False
hi bye False
bye goodbye False
bye by True
bye bye True
Upvotes: 0
Reputation: 6556
Try this way:
listOne = ['hello','hi','bye']
listTwo = ['goodbye','by']
for x in listTwo:
if any(x in e for e in listOne):
print(x)
it will print 'by', as 'by' is part of 'bye' in listOne
.
Upvotes: 3