在列表中查找子列表的开始和结束索引 [英] Find starting and ending indices of sublist in 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)
应返回:
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)
这篇关于在列表中查找子列表的开始和结束索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文