使用Python查找字符串中字符串列表中项目的索引
我正在寻找一种快速的方法来查找字符串中与项(一个或多个单词)匹配的所有索引。实际上我不需要列表中的索引,我需要字符串中的索引 我有一个单词列表和如下字符串:使用Python查找字符串中字符串列表中项目的索引,python,string,list,algorithm,indexof,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 = ['must', 'shall', 'may','should','forbidden','car',...]
string= 'you should wash the car every day'
desired output:
[1,4]# should=1, car=4
列表的长度有时可以超过数百项,字符串的长度可以超过数万项
我正在寻找一种如此快速的方法,因为它在每次迭代中被调用一千次
我知道如何使用循环实现它,并逐个检查所有项目,但它太慢了 一种解决方案是制作
单词设置而不是列表
,然后进行简单的列表理解:
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]
你可以使用字典
查找字典的时间复杂度为O(1)
你需要算法来解决这个问题
给定一组字符串和一个文本,它会在O(len+ans)
中查找给定文本集中所有字符串的匹配项,其中len
是文本的长度,ans
是答案的大小
它使用自动装置,可以根据您的需要进行修改。使用列表理解
print([string.split().index(i) for i in string.split() if i in words])
#[1,4]
单词可以有重复的元素吗?@AnuragWagh不可以not@Sina检查我的答案,看看它是否符合您的要求?它工作正常,但速度太慢,因此我提到我知道如何使用循环实现它,但速度太慢。请注意,字典操作是O(n)最坏情况和O(1)应为。您假定列表中的单词不是字符串中单词的子序列<代码>“让我们踢足球吧”
,[“脚”,“球”]
。
print([string.split().index(i) for i in string.split() if i in words])
#[1,4]