python - 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']
到目前为止,我自己无法弄清楚。也许可以使用两个循环并使用正则表达式?
解决方案
您可以使用关键字找到字符串的索引,然后使用第一次和最后一次出现的索引对值列表进行切片
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']
推荐阅读
- javascript - 如何在 glDatePicker 中禁用特定日期
- heroku - 部署到 heroku 会引发 webpack (package.json) 的问题
- spring-boot - @Query 不适用于 QueryDSL 谓词
- ios - 使用 Swift 4 搜索自定义 UITableCell 和过滤器的项目
- rest - REST 是开发视频播放 api 的好方法吗?
- c# - 我可以在 .NET Core 中获取私有构造函数吗?
- python - 当 np.nan 存在时 Pandas cumcount()
- directx - 如何强制执行 DirectX9 而不是 DirectX11
- c# - C#.net Crystal Report 在客户端机器上运行
- node.js - 禁用http端口时如何检查RabbitMQ是否启动并运行