【问题标题】:How Can I Check if Every Item in a List Appears Within Any Items in Another List?如何检查列表中的每个项目是否出现在另一个列表中的任何项目中?
【发布时间】:2021-02-26 06:38:50
【问题描述】:

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

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

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

我想检查 list1 中的每个字符串是否出现 in 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,即使我像第一个示例一样使用了测试列表。

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

【问题讨论】:

    标签: python list


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      这应该可行:

      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。

      【讨论】:

        【解决方案3】:
        all(
            any(
                word1 in map(str.lower, word2.split()) 
                for word2 in list2
            )
            for word1 in list1
        )
        

        根据您的输入有多好,您可以将map(str.lower, word2.split()) 替换为word2

        【讨论】:

          【解决方案4】:

          也许这有帮助

          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])
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2022-08-24
            • 1970-01-01
            • 1970-01-01
            • 2019-07-26
            • 2019-03-02
            • 1970-01-01
            • 2013-12-12
            • 1970-01-01
            相关资源
            最近更新 更多