检查列表中的每个字符串(所有字符串)是否至少是另一个字符串中的一个子字符串

时间:2020-05-14 04:57:23

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

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

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

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

例如,在此示例中,它将返回True

3 个答案:

答案 0 :(得分:8)

您可以将生成器表达式与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

答案 1 :(得分:1)

您可以使用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)       

答案 2 :(得分:-2)

如果满足列表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)