Sunday, 13 August 2017

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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...