This is my list:
text = ['direction','languag','mate','lan','diretion','diretions','non,'Diretion']
Using text.index(), how can I find the positions of words that are equal or similar to "direction" i.e diretion,diretions,Diretion ?
this is not an optimal solution:
[text.index("direction"),text.index("diretion"),text.index("diretions"),text.index("Diretion")]
I think that using a dictionary of similar words is an option but I don't know how to implement it. Please help
CodePudding user response:
We will do something like this, Please read how to implement dictionaries, it'd help you understand better
text = ['direction','languag','mate','lan','diretion','diretions','non','Diretion']
# making a dictionary with desired words
myDict = {'direction':1, 'diretions':1,'Diretion':1,'diretion':1}
# storing the answers in ans array
ans = []
and then you can run a for loop to get indices
for j in range(len(text)):
if text[j] in myDict:
ans.append(j)
CodePudding user response:
The index() method return the index of an element specified by value, otherwise it raise the exception ValueError (that you should handle with the try-except construct).
So, if you pass as a parameter a value similar, but which isn't contained in the list, you would get a ValueError exception.
The only way to do that is that you design and develop your own algorithm without rely on the index() method, which is useless, as I said.
A dictionary would be useless too, unless you find it a use in your own algorithm.
CodePudding user response:
You can use iterator enumerate(text)
to get the index of each word in the list and then filter our all similar words which will give index of filtered words
text_index = [index for index, word in enumerate(text) if word in ("direction","diretion","directions")]