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



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

list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
for string in lists:
strings = string.split()
print(strings)

字符串的示例输出:

['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'

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

combinations = any(i in list_1 for i in strings)

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

s1 = set(list_1)
if len(s1.intersection(strings)) >= 2:
#  do stuff

然而,如果同一项目在strings中出现两次,这不会触发,这可能是你想要的,也可能不是。在这种情况下,你可以做一些类似的事情:

if sum(s in s1 for s in strings) >= 2:
# do stuff

我显然迟到了。这基本上是schwobaseggl的解决方案包装为一个函数

mylist = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
mytest = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
def common_elements(mylist, mytest):
common_elements = list(set(mylist).intersection(mytest))
if len(common_elements)>2:
return common_elements
else:
pass

这应该有效:

string = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
n = 0
inv = []
for i in string:
if i in list_1:
inv.append(i)
n += 1
if n >= 2:
print(inv)

或者你可以把它放进一个定义中,让自己成为一个函数:

def check(string,list_1):
inv = []
for i in string:
if i in list_1:
inv.append(i)
if len(inv) >= 2:
return inv
else: return []
string = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
list_1 = ['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
print(check(string,list_1))

您也可以尝试这种"硬编码"方式

list1=['apple','soap','diet coke','banana','sweets','mash','fruit','veggies']
list2 = ['today', 'i','bought','banana','but','forgot','soap', 'and','veggies']
def check(list_1,list_2) :
common = list()
for i in list_1 :
if i in list_2 :
common.append(i)
if len(common) >=2 :
return common
else :
return "Less than two items are common"
try = check(list_1,list_2)

如果我没有错,你想知道两个列表有两个以上的相同元素吗?

def intersection(list_one, list_two):
intersection = set(list_one) & set(list_two)
if len(list(intersection)) > 1:
print(list(intersection))
return False

a = [1, 2, 3, 4]
b = [1, 8, 9, 10]
c = [1, 2, 5, 6]
intersection(a, b)  # return False
intersection(a, c)  # return [1, 2]

最新更新