Reputation: 23
For example: If I have 2 lists,
list1 = ["apple","banana","pear"]
list2 = ["Tasty apple treat", "Amazing banana snack", "Best pear soup"]
I would like to check if every string in list1 appears in any item in list2. So in the example, it would get True in return. But if list2 looked like this...
list2 = ["Tasty apple treat", "Best pear soup", "Delicious grape pie"]
...it would return false since "banana" doesn't appear in any items in the list.
I have tried by making a tfList that would hold True and False values and then I could just check if any items in the tfList were false.
tfList = []
for x in list1:
if (x in list2):
tfList.append(True)
else:
tfList.append(False)
I also tried this but it may have been a worse attempt:
if all(True if (x in list2) else False for x in list1):
The first one returned all False values and the second one didn't run the if statement as true and instead ran the else even though I used testing lists like the first examples.
**I'm very new to this so apologies if my attempts seem insane.
Upvotes: 0
Views: 53
Reputation: 51
Maybe this helps
list1 = ["apple","banana","pear"]
list2 = ["Tasty apple treat", "Amazing banana snack", "Best pear soup"]
#return true/false for presense of list1 in any of items in list2
tf_list = [i in x for i in list1 for x in list2]
# if all items in list1 in list2
tf_list_all = all([i in x for i in list1 for x in list2])
# if any of items of list1 is in list 2
tf_list_any = any([i in x for i in list1 for x in list2])
Upvotes: 0
Reputation: 1555
You want to check if each string of list1
is a sub-string of at least one element of list2
.
The reason your first approach returns always False
is because you are not checking if x
appears in each element of list2
, rather if x
is an element of list2
.
You could accomplish your goal by:
def appears_in(list1, list2):
for word in list1:
appears = False
for sentence in list2:
if word in sentence:
appears = True
break
if not appears:
return False
return True
Upvotes: 1
Reputation: 13934
all(
any(
word1 in map(str.lower, word2.split())
for word2 in list2
)
for word1 in list1
)
Depending on how nice your inputs are, you can replace map(str.lower, word2.split())
with word2
.
Upvotes: 0
Reputation: 109
This should work:
find = True
for word in list1:
auxFind = False
for phrase in list2:
if(word in phrase):
auxFind = True
if(not auxFind):
find = False
print(find)
What it does is verify if every word in list1 appears at least one time on list2 and return True if does find.
Upvotes: 0