簡體   English   中英

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

[英]Find indexes of items in list of string in an string with Python

我正在尋找一種快速的方法來查找字符串中與項目(一個或多個單詞)匹配的所有索引。 實際上我不需要列表中的索引我需要字符串中的索引。

我有一個單詞列表和一個像這樣的字符串:

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

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

有時列表的長度可能超過數百個項目和字符串超過數萬。

我正在尋找一種如此快速的方法,因為它在每次迭代中被調用一千次。

我知道如何用循環來實現它並一個一個地檢查所有項目,但它太慢了!

一種解決方案是set words而不是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]

為此,您需要Aho Corasick算法。

給定一組字符串和一個文本,它會在O(len+ans)的給定文本中找到該集合中所有字符串的出現,其中len是文本的長度,而ans是答案的大小。

它使用自動機,可以根據您的需要進行修改。

您可以使用字典查找字典的時間復雜度為 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]

使用列表理解,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM