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!

oliver13
  • 996
  • 2
  • 7
  • 19

1 Answers1

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

georg
  • 211,518
  • 52
  • 313
  • 390
  • 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 Apr 30 '13 at 09:04
  • 1
    @oliver13 Take a look at [list comprehensions in the docs](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) – TerryA Apr 30 '13 at 09:06
  • 2
    @oliver13: this is called a "generator expression". See e.g. http://stackoverflow.com/q/1756096/989121 for explanations. – georg Apr 30 '13 at 09:07
  • @Haidro: this isn't a list comprehension. – georg Apr 30 '13 at 09:08
  • Oh, I thought he was talking about the syntax of `for x in y`. My mistake then. – TerryA Apr 30 '13 at 09:09