使用Python在字符串列表中查找字符串列表中的项目的索引

问题描述 投票:0回答:1

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

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

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

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

列表的长度有时可以超过数百个项目,而字符串则可以成千上万。

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

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

python string list algorithm indexof
1个回答
0
投票

您尝试对words列表进行排序,然后对每个单词应用binary search。复杂度为O(n log n) + m* O(log n)

第一部分用于排序,第二部分用于搜索句子的m个单词。


0
投票

一种解决方案是用words 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]
© www.soinside.com 2019 - 2024. All rights reserved.