【问题标题】:Check if each string (all of them) on a list is a substring in at least one of the strings in another检查列表中的每个字符串(全部)是否是另一个字符串中至少一个字符串中的子字符串
【发布时间】:2020-08-30 12:42:38
【问题描述】:

我很难检查 python 列表中的所有字符串是否是另一个 Python 列表中任何字符串的子集。

示例: 我想检查list1 的每个字符串(全部)是否至少在list2 中的一个字符串中,如果是,请执行一些操作。

list1 = ['tomato', 'onions','egg']
list2 = ['Two tomatos', 'two onions','two eggs','salsa']

例如,在本例中,它将返回 True

【问题讨论】:

    标签: python python-3.x list substring subset


    【解决方案1】:

    您可以将生成器表达式与any/all 函数结合使用:

    >>> list1 = ['tomato', 'onions','egg']
    >>> list2 = ['Two tomatos', 'two onions','two eggs','salsa']
    >>> all(any(i in j for j in list2) for i in list1)
    True
    

    【讨论】:

    • 工作就像一个魅力!我正在使用 all() 但没有将它与 any() 结合使用谢谢先生!
    • 如果你错过了推理;您希望list1 中的所有 值与list2 中的任何 值之一匹配。
    【解决方案2】:

    您可以使用 list comprehensionanyall 来处理单个命令。

    list1 = ['tomato', 'onions','egg']
    list2 = ['Two tomatos', 'two onions','two eggs','salsa']
    result = all([any([keyword in string for string in list2]) for keyword in list1])       
    

    第一个列表解析[keyword in string for string in list2]检查关键字是否至少存在于list2的所有字符串中,并生成一个布尔列表。我们使用 any 来确定是否有任何结果是 True

    第二个列表解析建立在第一个列表解析[any([keyword in string for string in list2]) for keyword in list1] 之上,并检查所有关键字在list2 的所有字符串中最少出现。我们使用all 来检查所有结果是否为True

    正如@Selcuk 提到的,您可以使用generator expressions 更有效地做到这一点:语法真的非常接近列表推导:

    result = all(any(keyword in string for string in list2) for keyword in list1)       
    

    【讨论】:

      【解决方案3】:

      如果满足列表 1 中的单词存在于列表 2 的某个元素中的条件,您可以遍历列表并执行某些操作,例如:

      list1 = ['tomato', 'onions','egg']
      list2 = ['Two tomatos', 'two onions','two eggs','salsa']
      for i in list1:
          for j in list2:
              if i in j:
                  print("something to ", i, " and ", j)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-11
        • 2012-11-23
        • 2013-05-12
        • 2011-02-07
        • 1970-01-01
        • 2022-07-01
        • 1970-01-01
        相关资源
        最近更新 更多