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

标签 python string list algorithm indexof

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

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

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

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

有时列表的长度可以超过数百项,而字符串则可以达到数万。

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

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

最佳答案

一个解决方案是制作 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]

关于python - 使用 Python 在字符串列表中查找项目的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62173116/

相关文章:

java - String.format() 错误

javascript - 为什么这个 javascript 从 "h"中取出 "he"?

c - 分解预先格式化的字符串

python - 交换列表中的最大值和最小值

python - 为什么 statsmodels 不能重现我的 R 逻辑回归结果?

java - 在java和python中解析非常大的bz2 xml文件(逐个元素)

python - 这个 Python 列表推导式是按什么顺序执行的?

list - Erlang,列出 : find element with maximum defined by a fun

python - 如何在VSCode中自动将根目录添加到python路径中?

python - 如何按 mongodb 中 $geonear 聚合管道中的其他字段排序