Friday, September 28, 2018

How to get the index in the 'in' statement in Python





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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...