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', 'for', 'Sudan', '_s', 'policy', 'in', 'Darfur', '.']
前任。
seq0 = "Steven Spielberg"
seq1 = "the Chinese Government"
seq2 = "the Beijing Olympics"
输出应该是这样的:
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)
输出:
seq1 6
seq0 10
seq2 15
推荐阅读
- javascript - jquery根据查询字符串值更新锚标签的图像src
- javascript - 检查数组中的字符串是否包含另一个字符串 React Native
- r - 光栅投影到 UTM 到 R 中的 Lat-Lon
- c++ - 将任意数据传递给不接受“void* userarg”的 C++ 回调
- mapbox-gl-js - mapbox 创建、加载和编辑mbtiles的属性
- android - 如何将base64字符串发布到服务器?
- javascript - 样式未在组件中更新 - React
- php - CodeIgniter - 配置文件编辑后
- unix - 如何查找托管我的主目录和托管我的主目录的存储系统技术
- django - django inspectdb,检查期间如何写入多个表名