我目前正在尝试编写一个遍历序列 (x) 的代码,以搜索用户输入的单词。
下面是代码。
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
i = -1
while True:
s = input("Enter a word to search: ")
if s != "Quit":
try:
while i < len(x):
i = x.index(s, i+1)
print("found at index", i)
except ValueError:
print("Not found")
i = -1
else:
break
print("Goodbye")
上面的代码在迭代中运行良好,但在迭代序列后总是会返回 ValueError。我试图通过添加来纠正这个问题:
while i < len(x):
认为一旦到达序列末尾迭代就会停止,但在从序列中返回找到的值后它继续抛出异常。
例如,如果用户输入“9”,返回的是:
found at index 8
Not found
最佳答案
您正在尝试查找所有 个事件,但您不会找到上一个事件之后的下一个事件:
>>> 'abc'.index('a', 0)
0
>>> 'abc'.index('a', 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
你需要设置一个标志来表明你至少找到了一个匹配项,因为对于任意数量的匹配项都会抛出异常:
i = -1
try:
found = False
while i < len(x):
i = x.index(s, i+1)
print("found at index", i)
found = True
except ValueError:
if not found:
print("Not found")
但是如果您要扫描整个 x
列表无论如何,只需使用过滤器:
matches = [i for i, value in enumerate(x) if value == s]:
if not matches:
print('Not found')
for match in matches:
print("found at index", i)
如果你只需要找到一个匹配,第一个,你根本不需要使用循环:
try:
print("found at index", x.index(s))
except ValueError:
print("not found")
因为没有必要遍历起始位置。
关于python - 异常捕获甚至值是真的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16224657/