Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find starting and ending indices of sublist in list

I have a list:

greeting = ['hello','my','name','is','bob','how','are','you']

I want to define a function that will find the first and last index of a sublist in this list. Thus:

find_sub_list(['my','name','is'], greeting)

should return:

1, 3

Suggestions?

like image 547
David Y. Stephenson Avatar asked Jul 25 '13 23:07

David Y. Stephenson


People also ask

How do you check if a sublist is in a list Python?

issubset() function. The most used and recommended method to check for a sublist. This function is tailor made to perform the particular task of checking if one list is a subset of another.


1 Answers

If you want multiple matches, this works:

greeting = ['hello','my','name','is','bob','how','are','you','my','name','is']

def find_sub_list(sl,l):
    results=[]
    sll=len(sl)
    for ind in (i for i,e in enumerate(l) if e==sl[0]):
        if l[ind:ind+sll]==sl:
            results.append((ind,ind+sll-1))

    return results

print find_sub_list(['my','name','is'], greeting) 
# [(1, 3), (8, 10)]

Or if you just want the first match:

greeting = ['hello','my','name','is','bob','how','are','you','my','name','is']

def find_sub_list(sl,l):
    sll=len(sl)
    for ind in (i for i,e in enumerate(l) if e==sl[0]):
        if l[ind:ind+sll]==sl:
            return ind,ind+sll-1

print find_sub_list(['my','name','is'], greeting)    
# (1, 3)
like image 114
dawg Avatar answered Sep 30 '22 19:09

dawg