2013-04-25 118 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") 

多次出現的位置雖然有可能也是一種簡單的方法。