Reputation: 2825
strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']
I want to find the string that includes both bird and bag in the list strings
, regardless of order. So the result for only the second element in strings
should be true and the rest should be false.
The output I want:
False
True
False
words
do not necessarily need to be stored in list, and I know that regex
could do a similar thing but I would prefer to use other ways than regex
because my words are mandarin chinese which requires some complicated use of regex than english.
Upvotes: 3
Views: 12586
Reputation: 3049
This is it:
for substring in strings:
k = [ w for w in words if w in substring ]
print (len(k) == len(words) )
Upvotes: 1
Reputation: 481
For variable number of words, without using the split function.
strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']
for string in strings:
print(all(word in string for word in words))
Upvotes: 1
Reputation: 1030
Use of function all() would be best option here, but point is doing without for loop. Here is solution using map/lambda function.
strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']
map(lambda x: all(map(lambda y:y in x.split(),words)),strings)
output would be:
[False, True, False]
However, Naive Solution is for beginner:
for string in strings:
count_match=0
for word in words:
if word in string.split():
count_match+=1
if(count_match==len(words)):
print "True"
else:
print "False"
And output would be :
False
True
False
Upvotes: 1
Reputation: 2047
strings = ['I have a bird', 'I have a bag and a bird', 'I have a bag']
words = ['bird','bag']
for string in strings:
stringlist = string.split()
word1 , word2 = words
if word1 in stringlist and word2 in stringlist:
print(True)
else:
print(False)
Result
False True False
Upvotes: 2
Reputation: 6794
List comprehension will work combined with the all
function:
[all([k in s for k in words]) for s in strings]
This results in the following on your example:
[False, True, False]
Upvotes: 8