I'm looking for a fast approach to find all the indexes in string which match with items (one or multiple words). Actually I do not need index in list I need index in string.
I have a list of words and an string like these:
words = ['must', 'shall', 'may','should','forbidden','car',...]
string= 'you should wash the car every day'
desired output:
[1,4]# should=1, car=4
The length of list some times can be more than hundreds of items and string more that tens of thousands.
I'm looking for a so fast approach because it is called a thousand times in each iteration.
I know how to implement it with loops and check all the items one-by-one but it's so slow!
One solution is make words set instead of list and then do simple list comprehension:
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)
Prints:
[1, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With