在列表中查找子列表的开始和结束索引

Dav*_*son 10 python search list sublist

我有一个清单:

greeting = ['hello','my','name','is','bob','how','are','you']
Run Code Online (Sandbox Code Playgroud)

我想定义一个函数,它将在此列表中找到子列表的第一个和最后一个索引.从而:

find_sub_list(['my','name','is'], greeting)
Run Code Online (Sandbox Code Playgroud)

应该返回:

1, 3
Run Code Online (Sandbox Code Playgroud)

建议?

daw*_*awg 11

如果你想要多个匹配,这有效:

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)]
Run Code Online (Sandbox Code Playgroud)

或者如果你只想要第一场比赛:

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)
Run Code Online (Sandbox Code Playgroud)