在列表中查找子列表的开始和结束索引
问题描述:
我有一个列表:
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)
应返回:
1, 3
建议?
答
如果您要进行多个匹配,则可以这样做:
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)