我写了一个if声明如下:
if word in vocab:
print word
Run Code Online (Sandbox Code Playgroud)
但是,我也想知道匹配的word索引vocab.
有没有办法在Python中可以做到这一点?
我只是提出了一个vocab.index(word)用于获取索引的解决方案,但这种方式通过数组两次(一个在if语句中,一个调用index()).我想知道应该有更多的效率方法.
谢谢.
为避免一个循环,您可以使用一个try-except子句(不使用if ... in ...:)
try:
i = vocab.index(word)
except ValueError as e:
print e # Optional
i = -1
Run Code Online (Sandbox Code Playgroud)