首页 > 解决方案 > Python:在包含关键字的字符串之间提取子列表

问题描述

我有一个字符串列表,现在我想提取包含特定关键字(包括这两个字符串)的两个字符串之间的所有字符串。

example_list = ['test sentence', 'the sky is blue', 'it is raining outside', 'mic check', 'vacation time']
keywords = ['sky', 'check']

我想要达到的结果:

result = ['the sky is blue', 'it is raining outside', 'mic check']

到目前为止,我自己无法弄清楚。也许可以使用两个循环并使用正则表达式?

标签: pythonstringlistsubstringsublist

解决方案


您可以使用关键字找到字符串的索引,然后使用第一次和最后一次出现的索引对值列表进行切片

indices = [i for i, x in enumerate(example_list) if any(k in x for k in keywords)]
result = example_list[indices[0]:indices[-1] + 1]
# ['the sky is blue', 'it is raining outside', 'mic check']

推荐阅读