繁体   English   中英

如何检查列表中的每个项目是否出现在另一个列表中的任何项目中?

[英]How Can I Check if Every Item in a List Appears Within Any Items in Another List?

例如:如果我有 2 个列表,

list1 = ["apple","banana","pear"]

list2 = ["Tasty apple treat", "Amazing banana snack", "Best pear soup"]

我想检查 list1 中的每个字符串是否出现list2 中的任何项目中。 所以在这个例子中,它会得到 True 作为回报。 但如果 list2 看起来像这样......

list2 = ["Tasty apple treat", "Best pear soup", "Delicious grape pie"]

...它会返回 false,因为“香蕉”没有出现在列表中的任何项目中。

我尝试制作一个包含 True 和 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,即使我像第一个示例一样使用了测试列表。

**如果我的尝试看起来很疯狂,我对此很抱歉。

您想检查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

这应该有效:

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。

all(
    any(
        word1 in map(str.lower, word2.split()) 
        for word2 in list2
    )
    for word1 in list1
)

根据您的输入有多好,您可以将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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM