oliver13
oliver13

Reputation: 1036

Comparing the items of two lists in Python

I read numerous questions on related issues, but none of them answers my question. I have two lists:

List A = ['nike', 'adidas', 'reebok']

List B = ['sneakers', 'sneaker shoes', 'adidas shoes', 'nike', 'any shoe', 'all nikes', 'a nike shoe']

Now, I want to see if the items of List A exist somewhere in B, so that it returns:

List result: [False, False, True, True, False, True, True]

True represents the instance in List B where an item of A is matched. So far, I have used this code which seems terribly inefficient.

for j in range(len(lista)):
    for k in b:
    if j in k: 
        lista[j] = 'DELETE'

cuent = lista.count('DELETE')

for i in range(cuent):
    lista.remove('DELETE')

Thanks in advance and sorry if there is indeed an answer to this - after an hour I have lost all hope of finding it in the stackoverflow-universe :)

EDIT: Sorry for not making myself clear - I am NOT looking for exact matches, I am looking for phrase matches. Sorry again!

Upvotes: 1

Views: 324

Answers (1)

georg
georg

Reputation: 214959

Maybe

keywords = ['nike', 'adidas', 'reebok']
items = ['sneakers', 'sneaker shoes', 'adidas shoes', 'nike', 'any shoe', 'all nikes', 'a nike shoe']
bits = [any(keyword in item for keyword in keywords) for item in items]

or better

import re
regex = re.compile(r'%s' % '|'.join(keywords))
bits = [bool(regex.search(x)) for x in items]

From my understanding, you want to ignore word boundaries (e.g. "nike" matches "all nikes"), to search full words only, change the above expression to r'\b(%s)\b'.

Upvotes: 5

Related Questions