首页 > 解决方案 > 使用Python在字符串中查找字符串列表中项目的索引

问题描述

我正在寻找一种快速的方法来查找字符串中与项目(一个或多个单词)匹配的所有索引。实际上我不需要列表中的索引我需要字符串中的索引。

我有一个单词列表和一个像这样的字符串:

words = ['must', 'shall', 'may','should','forbidden','car',...]
string= 'you should wash the car every day'

desired output:
[1,4]# should=1, car=4

有时列表的长度可能超过数百个项目和字符串超过数万。

我正在寻找一种如此快速的方法,因为它在每次迭代中被调用一千次。

我知道如何用循环来实现它并一个一个地检查所有项目,但它太慢了!

标签: pythonstringlistalgorithmindexof

解决方案


一种解决方案是 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]

推荐阅读