【问题标题】:Find indexes of items in list of string in an string with Python使用Python在字符串中查找字符串列表中项目的索引
【发布时间】:2020-06-03 12:42:52
【问题描述】:

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

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

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

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

列表的长度有时可能超过数百项,字符串也可能超过数万。

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

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

【问题讨论】:

  • 单词可以有重复的元素吗?
  • @AnuragWagh 不,他们不能
  • @Sina 看看我的回答是否符合你的要求?

标签: python string list algorithm indexof


【解决方案1】:

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

【讨论】:

  • 它可以工作,但它太慢了,所以我提到我知道如何用循环实现它,但它太慢了
【解决方案2】:

您需要Aho Corasick 算法。

给定一组字符串和一个文本,它会在O(len+ans) 的给定文本中找到该集合中所有字符串的出现次数,其中len 是文本的长度,ans 是答案的大小.

它使用自动机,可以根据您的需要进行修改。

【讨论】:

    【解决方案3】:

    您可以使用字典 查找字典的时间复杂度是 O(1)

    string = 'you should wash the car every day'
    
    wordToIndex = {word: index for index, word in enumerate(string.split())}
    
    words = ['must', 'shall', 'may','should','forbidden','car']
    
    result = [wordToIndex[word] for word in words if word in wordToIndex]
    
    # [1,4]
    

    【讨论】:

    • 应该注意字典操作是 O(n) 最坏情况和 O(1) 预期的。
    • 您假设列表中的单词不是字符串中单词的子序列。 "Let's play football", ["foot","ball"].
    【解决方案4】:

    使用列表理解,

    print([string.split().index(i) for i in string.split() if i in words]) 
    #[1,4]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-01
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2015-10-05
      • 1970-01-01
      相关资源
      最近更新 更多