在python中的列表中查找序列的索引 [英] Find indexes of sequence in list in python
本文介绍了在python中的列表中查找序列的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很新,我希望它不太明显,但是我似乎无法为以下问题找到一个简短而准确的答案.
I am quite new and I hope it's not too obvious, but I just can't seem to find a short and precise answer to the following problem.
我有两个列表:
a = [2,3,5,2,5,6,7,2]
b = [2,5,6]
我想查找第二个列表(b
)的所有索引何时在第一个列表(a
)中,以便得到如下内容:
I would like to find when all the indexes of the second list (b
) are in the first list (a
), so that I get something like this:
索引:3, 4, 5
或b = a[3:6]
推荐答案
具有列表理解功能:
>>> [(i, i+len(b)) for i in range(len(a)) if a[i:i+len(b)] == b]
[(3, 6)]
或带有for循环:
>>> indexes = []
>>> for i in range(len(a)):
... if a[i:i+len(b)] == b:
... indexes.append((i, i+len(b)))
...
>>> indexes
[(3, 6)]
这篇关于在python中的列表中查找序列的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文