在python中的列表中找到子列表的位置 [英] Find the position of sublist in a list in python
问题描述
例如,我在Python中有两个列表x和y.假设 x = [0,1,2,3,4,5,6,7]
和 y = [3,4,5]
,显然y是x的子列表,而子列表y在x中的位置是 3
.换句话说,我试图获得一个判断一个列表是否为另一个列表中的子列表的函数.如果是这样,我也想弄清楚子列表的位置.
For example, I have two list x and y in Python. Supposing x = [0,1,2,3,4,5,6,7]
and y = [3,4,5]
, it is clear that y is a sublist of x and the position of sublist y in x is 3
. In other words,I'm trying to get a function that judges whether a list is a sublist in another list. If so,I would like to figure out the position of the sublist as well.
我不知道我是否可以使用任何现成的功能.如果没有,那么有谁知道我如何使用某种有效的方法来实现它.
I don't know if there has any off-the-shelf function I can use. If not, does anyone have an idea of how I can achieve it using some effective method.
感谢您的任何帮助!
推荐答案
x = [0,1,2,3,4,5,6,7]
y = [3,4,5]
occ = [i for i, a in enumerate(x) if a == y[0]]
for b in occ:
if x[b:b+len(y)] == y:
print 'YES-- SUBLIST at : ', b
break
if len(occ)-1 == occ.index(b):
print 'NO SUBLIST'
break
这篇关于在python中的列表中找到子列表的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!