Как проверить, встречается ли какая-либо комбинация двух элементов списка в списке - PullRequest
1 голос
/ 30 апреля 2020

Мне интересно, есть ли способ проверить, существует ли какая-либо комбинация из более чем двух элементов из списка в другом списке?

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)

Ответы [ 5 ]

4 голосов
/ 30 апреля 2020

Вы можете использовать установить пересечение и проверить полученный размер:

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
1 голос
/ 30 апреля 2020

Я опоздал, видимо. Это в основном решение Швобасеггла , заключенное в функцию

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
0 голосов
/ 30 апреля 2020

Если я не ошибаюсь, вы хотите узнать, что 2 списка имеют более 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]
0 голосов
/ 30 апреля 2020

Вы можете попробовать этот "жестко запрограммированный" способ тоже

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)
0 голосов
/ 30 апреля 2020

Это должно работать:

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

...