Python 在列表中查找单词的特定顺序

Python 在列表中查找单词的特定顺序,python,Python,我需要在python中找到列表中特定字符串序列的起始索引 例如 list = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against', 'China', '_s', 'backing

我需要在python中找到列表中特定字符串序列的起始索引

例如

list = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against', 'China', '_s', 'backing', 'for', 'Sudan', '_s', 'policy', 'in', 'Darfur', '.']

输出应如下所示:

10
6
15

您可以简单地迭代您的单词列表,并在每个索引处检查以下单词是否匹配您的任何序列

words = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against', 'China', '_s', 'backing', 'for', 'Sudan', '_s', 'policy', 'in', 'Darfur', '.']\

seq0 = "Steven Spielberg"
seq1 = "the Chinese Government"
seq2 = "the Beijing Olympics"

sequences = {'seq{}'.format(idx): i.split() for idx, i in enumerate([seq0, seq1, seq2])}

for idx in range(len(words)):
    for k, v in sequences.items():
        if idx + len(v) < len(words) and words[idx: idx+len(v)] == v:
            print(k, idx)
您可以执行以下操作:

输出:

十,

六,

十五


注意,如果没有找到序列,您将得到-1。

Thank you@Sayse的副本。
words = ['In', 'a', 'gesture', 'sure', 'to', 'rattle', 'the', 'Chinese', 'Government', ',', 'Steven', 'Spielberg', 'pulled', 'out', 'of', 'the', 'Beijing', 'Olympics', 'to', 'protest', 'against', 'China', '_s', 'backing', 'for', 'Sudan', '_s', 'policy', 'in', 'Darfur', '.']\

seq0 = "Steven Spielberg"
seq1 = "the Chinese Government"
seq2 = "the Beijing Olympics"

sequences = {'seq{}'.format(idx): i.split() for idx, i in enumerate([seq0, seq1, seq2])}

for idx in range(len(words)):
    for k, v in sequences.items():
        if idx + len(v) < len(words) and words[idx: idx+len(v)] == v:
            print(k, idx)
seq1 6
seq0 10
seq2 15
def find_sequence(seq, _list):
    seq_list = seq.split()
    all_occurrence = [idx for idx in [i for i, x in enumerate(_list) if x == seq_list[0]] if seq_list == list_[idx:idx+len(seq_list)]]
    return -1 if not all_occurrence else all_occurrence[0]
for seq in [seq0, seq1, seq2]:
    print(find_sequence(seq, list_))