Home > Net >  Python: search in list by multiple consecutive items
Python: search in list by multiple consecutive items

Time:03-22

is it possible somehow to search in list by multiple items and get all occurences. So the idea is to search for two/three/... consecutive items in list.

For example we have a list:

['orange','banana','apple','orange','apple','banana','banana','kiwi','orange','banana','kiwi','orange','kiwi','kiwi','banana','orange','apple']

and I need to get all occurences of 'orange', 'banana'.

But not each occurence where orange or banana are in list, but exactly where orange is followed by item banana. I guess result in this case would be index of orange, since its first.

I assume result would find from mentioned list 3 occurences on idexes:

  • 'orange','banana' 0 index
  • 'orange','banana' 8 index
  • 'orange','banana' 14 index

CodePudding user response:

a = ['orange','banana','apple','orange','apple','banana','banana','kiwi','orange','banana','kiwi','orange','kiwi','kiwi','banana','orange','apple']
m = [i for i in range(0, len(a)-1) if 'orange' 'banana' == a[i] a[i 1] or 'banana' 'orange' == a[i] a[i 1]]
print(m)
b = 0
for i in m:
    b = i   2
    print(a[i:b])

Answered. Will it suit you?

CodePudding user response:

try this... i think it will hepls you...

lis = ['orange','banana','apple','orange','apple','banana','banana','kiwi','orange','banana','kiwi','orange','kiwi','kiwi','banana','orange','apple']
find_values = ['orange','banana']
for i,j in zip(lis,range(len(lis))):
    if i in find_values and lis[j 1] in find_values:
        if i != lis[j 1]:
            res = i   " "   lis[j   1]   " "   str(j)   " index"
            print(res)
  • Related