Alsphere
Alsphere

Reputation: 533

Searching in three elements before and after a specific word in list

I have list of string, my main word is "any" and I want to search for the in any three words before or after the "any", I tried this:

list1 = ['I','love','any','kind','of','7up','as','drink']
soda = ['7up','pepsi','sprite','fanta']
fruit= ['orange','apple','banana','pineapple']

j = 0
while list1[j]:
    if list1[j] == 'any' and list1[j - 1:j - 3] == 'love':
        if list1[j + 1:j + 3] in soda:
            print "loving soda"
        elif list1[j + 1:j + 3] in fruit:
            print "loving fruit"
        else:
            pass
    j += 1
    if j == len(list1):
        break

I tried to slice the list and search in sliced list but it doesn't work for me, sometimes no output sometimes index out of range. I think there is better way to do it. I do not use builtin functions in my code but it fine if that would solve the problem. I want to check if any of three words before "any" in list1 and any three words after the word "any" in list1 that occur in any list soda or fruit

Upvotes: 0

Views: 63

Answers (1)

augurar
augurar

Reputation: 13016

To test if any element in a slice meets some condition, use the any function with a generator expression.

For example, instead of:

list1[j - 1:j - 3] == 'love'

use:

any(list1[i] == 'love' for i in xrange(j-1, j-3))

or:

any(e == 'love' for e in list1[j-1:j-3])

Upvotes: 2

Related Questions