2017-01-05 39 views
1

編輯澄清:我試圖做到這一點,需要我建立接收的元素,一個元組和的情況下,該元素是在元組功能的學校鍛鍊,它返回它的相反,即位置:如何通過try/except來正確處理KeyError異常?

findInTupleA (1 , (1,2,3,1) 

打印

[3, 0] 

但如果該元素沒有在元組存在,KeyError應發說:「元素不是在元組」。

def findInTupleA(elem,tuplo): 
    lista_indices = [] 
    i = 0 
    while i < len(tuplo): 
     try: 
      if tuplo[i] == elem: 
       lista_indices.append(i) 
      i = i + 1 
     except KeyError: 
      return "element not in tuple" 

    if len(lista_indices)>=1: 
     return lista_indices[::-1] 
    else: 
     return lista_indices 

不過它不工作的打算,因爲如果我給它元件1元組(2,3),它返回一個空列表,而不是關鍵錯誤,而我要問,reverse()不工作在第二個if,不知道爲什麼。

P.S.如果您想對我可以改進代碼的方式發表評論,它會非常棒,對於斷言部分也是如此!

+0

爲什麼? 'tuplo'中的ele不起作用? –

+0

請修復您的代碼縮進。 –

+1

請修復您的縮進。正如所寫的,該程序在語法上不正確。 – DyZ

回答

4

這聽起來像你對我誤解了你的任務。我認爲您不需要使用tryexcept來捕捉函數中的異常,而是應該自己提升異常(也可以使用函數外部的try/except來處理它)。

嘗試這樣的東西多了,看它是否確實你需要什麼:

def findInTupleA(elem,tuplo): 
    lista_indices = []  
    i = 0 
    while i < len(tuplo): 
     if tuplo[i] == elem: 
      lista_indices.append(i) 
     i = i + 1 

    if len(lista_indices) >= 1: 
     return lista_indices 
    else: 
     raise IndexError("element not in tuple") 
+0

這解決了,如果我錯了,糾正我,我們正常運行循環,然後檢查輸出列表是否爲空,如果是,它會引發異常? – stasisOo

+1

是的,這正是這個代碼所做的。你可以在循環之前用'if elem in tuplo'來檢查元素,但'in'運算符與你的顯式循環基本上是一樣的,所以單獨的檢查有點傻。我不確定'IndexError'是在這種情況下引發的最合適的異常(「ValueError」會更自然),但是您應該符合您爲您的任務提供的規範。 – Blckknght

2

我認爲你的問題在於縮進。我想,你的目標是什麼,是...

def findInTupleA(elem,tuplo): 
    lista_indices = [] 
    i = 0 
    while i < len(tuplo): 
     try: 
      if tuplo[i] == elem: 
       lista_indices.append(i) 
     except KeyError: 
      return "element not in tuple" 
     i = i + 1 

    if len(lista_indices)>=1: 
     return lista_indices[::-1] 
    else: 
     return lista_indices 
+0

當我運行findInTupleA(1,(0,2,3,4))它返回[]而不是KeyError消息 – stasisOo

+0

看看這個答案:http://stackoverflow.com/questions/2191699/find-an - 元素-IN-A-列表的元組 –

3

如何檢查是否元素index是在元組。如果元素不存在,則異常ValueError上返回element not in tuple這樣的:

def in_tuple(elem, tuplo): 

    try: 
     return tuplo.index(elem) 
    except ValueError: 
     return 'element not in tuple' 

print in_tuple(1, (2, 3)) 
+0

不是我一直在尋找,但它的偉大信息和偉大工程,感謝 – stasisOo

+0

@stasisOo沒有問題,感謝給予好評! –