I wrote an if statement like:
if word in vocab:
print word
However, I also would like to know the matched word index in vocab.
Is there any way in Python can do this?
I just come up a solution that use vocab.index(word) to get the index, but this way go through the array twice (one in if statement, one call index()). I wonder there should be more efficiency method.
Thanks.
Answer
To avoid one loop, you can use a try-except clause (without using if ... in ...:)
try:
i = vocab.index(word)
except ValueError as e:
print e # Optional
i = -1
No comments:
Post a Comment