我正在寻找一种快速方法来查找字符串中与项目(一个或多个单词)匹配的所有索引。实际上我不需要列表中的索引我需要字符串中的索引。
我有一个单词列表和一个像这样的字符串:
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/