2013-04-25 39 views
1

我目前正试图编写一个迭代序列(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 

回答

4

你正在努力寻找所有出现,但你不会找到下一个出现过最后一个:

>>> '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") 

,因为没有需要循环起始位置即可。

+0

谢谢!这个答案是完美的,像魅力一样工作。虽然我也通过改变'while(i Keith 2013-04-25 21:25:20

+0

实际上,第一种方法是完美的,但第二种方法对所有搜索产生-1索引的结果。 – Keith 2013-04-25 22:46:04

+0

哪种方法? 'found'标志,列表理解用'enumerate()'或简单的'.index()'表示第一次匹配? – 2013-04-25 22:50:41

0

的原因,你总是得到ValueError是因为你总是继续通过项目列表中的迭代,直到你得到一个ValueError。您需要在内部while循环中包含某种条件,以便它在找到元素时退出。更好的是,做下面我发布的编辑。

取而代之的是:

try: 
    while i < len(x): 
     i = x.index(s, i+1) 
     print("found at index", i) 
except ValueError: 
    print("Not found") 
i = -1 

试试这个:

try: 
    print("found at index", x.index(s)) 
except ValueError: 
    print("not found") 

简单得多。

0

首先得到一个计数,然后让事件的索引,如果你想在列表

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] 
n = 0 
while True: 
    s = input("Enter a word to search: ") 
    if s != "Quit": 
     n = x.count(s) 
     if s == 0: 
      print('not found') 
     else: 
      i = -1 
      while n > 0: 
       print('found at index:', x.index(s,i+1)) 
       n = n - 1 
    else: 
     break 
print("Goodbye") 

多次出现的位置虽然有可能也是一种简单的方法。