如何检查列表中是否出现两个列表项的任意组合

msa*_*msa 2 python list-comprehension list python-3.x

我想知道是否有办法检查一个列表中两个以上项目的组合是否存在于另一个列表中?

list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']

for string in lists:
    strings = string.split()
    print(strings)
Run Code Online (Sandbox Code Playgroud)

字符串的示例输出:

['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']# this line should identify 'banana', 'soap' and 'veggies'
['maybe', 'there','are','more','sweets','left','later'] # this line should be ignored, because not more than 2 items of the list are in it 
['food', 'shopping','is','boring','and','i','hate','mash','with','veggies']# this line should identify 'mash' and 'veggies'
Run Code Online (Sandbox Code Playgroud)

我知道通过使用这段代码,我至少可以检查是否有任何元素出现在字符串中:

  combinations = any(i in list_1 for i in strings)
Run Code Online (Sandbox Code Playgroud)

sch*_*ggl 5

您可以使用设置交集并检查结果大小:

s1 = set(list_1)

if len(s1.intersection(strings)) >= 2:
    #  do stuff
Run Code Online (Sandbox Code Playgroud)

但是,如果相同的项目出现两次,strings其中可能是您​​想要的,也可能不是,这将不会触发。在这种情况下,您可以执行以下操作:

if sum(s in s1 for s in strings) >= 2:
    # do stuff
Run Code Online (Sandbox Code Playgroud)

  • 我为这种情况添加了一种方法。 (2认同)