Python 如何检查列表中的每个项目是否出现在另一个列表中的任何项目中?
例如: 如果我有两张名单Python 如何检查列表中的每个项目是否出现在另一个列表中的任何项目中?,python,list,Python,List,例如: 如果我有两张名单 list1 = ["apple","banana","pear"] list2 = ["Tasty apple treat", "Amazing banana snack", "Best pear soup"] 我想检查列表1中的每个字符串是否出现在列表2中的任何项目中。 所以在这个例子中,它会反过来变成真的。 但是如果列表2看起来像这样 list
list1 = ["apple","banana","pear"]
list2 = ["Tasty apple treat", "Amazing banana snack", "Best pear soup"]
我想检查列表1中的每个字符串是否出现在列表2中的任何项目中。
所以在这个例子中,它会反过来变成真的。
但是如果列表2看起来像这样
list2 = ["Tasty apple treat", "Best pear soup", "Delicious grape pie"]
…它将返回false,因为“香蕉”不出现在列表中的任何项目中
我尝试制作一个包含真值和假值的tfList,然后我可以检查tfList中的任何项是否为假
tfList = []
for x in list1:
if (x in list2):
tfList.append(True)
else:
tfList.append(False)
我也尝试过,但可能是更糟糕的尝试:
if all(True if (x in list2) else False for x in list1):
第一个返回所有False值,第二个没有将if语句作为true运行,而是运行else,尽管我使用了与第一个示例类似的测试列表
**我对此很陌生,因此,如果我的尝试看起来很疯狂,我深表歉意。这应该有效:
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)
它所做的是验证list1中的每个单词是否在list2上至少出现一次,如果确实找到,则返回True。您想检查list1的每个字符串是否是list2的至少一个元素的子字符串 第一种方法总是返回
False
的原因是,您没有检查x
是否出现在list2
的每个元素中,而是检查x
是否是list2
的一个元素
您可以通过以下方式实现您的目标:
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
根据您的输入有多好,您可以将map(str.lower,word2.split())
替换为word2
也许这会有所帮助
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])
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])