-2
list1 = ['abra','hello','cfre']

list2 = ['dacc','ex','you', 'fboaf']

ttext = 'hello how are you?'

for i,j in zip(list1, list2):
    print i,j

abra dacc
hello ex
cfre you
None fboaf

if (i in ttext and j in ttext):

Hello, this compare the same index of the lists, here i want to find if there's 'hello' and 'you' in ttext

What is the best way to do that ?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
super trainee
  • 117
  • 2
  • 11

1 Answers1

4

You can use itertools.product like this

>>> list1 = ['abra', 'hello', 'cfre']
>>> list2 = ['dacc', 'ex', 'you', 'fboaf']
>>> ttext = 'hello how are you?'
>>> from itertools import product
>>> for word1, word2 in product(list1, list2):
...     print word1, word2, (word1 in ttext and word2 in ttext)
...
abra dacc False
abra ex False
abra you False
abra fboaf False
hello dacc False
hello ex False
hello you True
hello fboaf False
cfre dacc False
cfre ex False
cfre you False
cfre fboaf False

itertools.product computes the cartesian product of the iterables passed to it. Now, we check if all the items in product appears in the ttext.


You can actually make it generic like this

>>> ttext = 'hello how are you?'
>>> for words in product(list1, list2):
...     print(words, all(word in ttext for word in words))

The all function will return True only when all the elements of the iterable passed to it are Truthy. In your case, it just checks if each of the words in the words tuple is present in ttext.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • for word1, word2 in product(list1, list2): if (word1 in ttext and word2 in ttext): print 'ok' – super trainee Jan 04 '16 at 14:22
  • Using `it.product(*((word for word in lst if word in ttext) for lst in (list1, list2)))` should be faster because it first filters the right words and then calculates the product. Also, `word in ttext` is not the right test for words since it matches `ell` in `hello` as well. Convert `ttext` to a list of strings, such as with `re.findall(r'\w+', ttext)`. – eumiro Jan 04 '16 at 14:28
  • @thefourtheye now if i have more than 2 lists for exemple i have a list of lists and i want to make sure i only have a word of one list ? – super trainee Jan 04 '16 at 14:45
  • @supertrainee You can use the generic approach I mentioned at the bottom, with a small change. `for words in product(*list_of_lists):` – thefourtheye Jan 04 '16 at 14:51
  • @supertrainee I am not able to open it – thefourtheye Jan 04 '16 at 17:34