首页 > 解决方案 > 在列表中查找特定的单词序列

问题描述

我需要在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', '.']

前任。

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

输出应该是这样的:

10
6
15

标签: python

解决方案


您可以简单地遍历您的单词列表并检查每个索引是否与您的任何序列匹配。

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

推荐阅读