How to get the index in the 'in' statement in Python
This question already has an answer here:
要避免一个循环,可以使用try-except
子句(不使用if ... in ...:
try:
i = vocab.index(word)
except ValueError as e:
print e # Optional
i = -1
This is a case where I wish I could do assignment in an if statement, but I can't so this is the solution:
If vocab
is a list
:
try:
index = vocab.index(word)
except ValueError:
pass
else:
print index, word
if vocab
is a str
:
index = vocab.find(word)
if index >= 0:
print index, word
def getindex(iterable,target):
for idx,value in enumerate(iterable):
if value==target: return idx
return -1
Note that this WILL NOT work if you're trying to find a substring in a string (as I'm assuming, since you're doing if word in vocab
. In that case you really should do:
try: idx = iterable.index(target)
except ValueError as e: # Not found
# Handle it
If you try to use the getindex
function above, it will always return -1
for any value len(target) > 1
since it will break your iterable into its smallest iteration, which is by-letter for strings.
上一篇: 在Python中按值获取JSON列表索引
下一篇: 如何获得Python中'in'语句的索引