1

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!

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

5 Comments

This is perfect - I am not yet familiar with the very short "(keyword in item for keyword in keywords)"-expression - do you know where I can learn more about that? Thanks!
@oliver13 Take a look at list comprehensions in the docs
@oliver13: this is called a "generator expression". See e.g. stackoverflow.com/q/1756096/989121 for explanations.
@Haidro: this isn't a list comprehension.
Oh, I thought he was talking about the syntax of for x in y. My mistake then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.