python - 使用Python在字符串中查找字符串列表中项目的索引
问题描述
我正在寻找一种快速的方法来查找字符串中与项目(一个或多个单词)匹配的所有索引。实际上我不需要列表中的索引我需要字符串中的索引。
我有一个单词列表和一个像这样的字符串:
words = ['must', 'shall', 'may','should','forbidden','car',...]
string= 'you should wash the car every day'
desired output:
[1,4]# should=1, car=4
有时列表的长度可能超过数百个项目和字符串超过数万。
我正在寻找一种如此快速的方法,因为它在每次迭代中被调用一千次。
我知道如何用循环来实现它并一个一个地检查所有项目,但它太慢了!
解决方案
一种解决方案是 makewords
set
而不是list
然后进行简单的列表理解:
words = {'must', 'shall', 'may','should','forbidden','car'}
string= 'you should wash the car every day'
out = [i for i, w in enumerate(string.split()) if w in words]
print(out)
印刷:
[1, 4]
推荐阅读
- xcode - 奇怪的 NSOutlineView 崩溃
- java - 如何比较两个字符串以找到公共子字符串
- ios - 仅在 UIIMagePictureController 中查看视频
- java - 将数字转换为星号
- python - pandas:根据值计算频率(直方图)
- ios - 如何在 ios 中启用 pjsip 蓝牙?
- vue.js - 使用 'v-for' 构建 HTML 选择选项并将键分配为选项值
- javascript - 防止 Ajax 聊天加载到页面顶部
- java - 使用 Spring JPA 将文件转换为 MultiPartFile
- jquery - 不允许在字符串开头使用字母的正则表达式