2017-02-24 132 views
0

我想寫一個遞歸函數,如果元素在嵌套列表中,它將返回True,否則它的假不是。到目前爲止,我的代碼僅適用於某些元素:如何使用遞歸在嵌套列表中查找元素?

def inthere(ls, s): 
    if s in ls: 
     return True 
    else: 
     for thing in ls: 
      if isinstance(thing, list): 
       return inthere(thing,s) 

當我運行:

A=[[2,4],[6,[[[8],10]],12],14,16] 
print(inthere(A,12)) #Should return True, but does not. 
print(inthere(A,2)) #Returns True, as it should. 

我確實失去了一些東西,我似乎無法告訴,我感謝所有幫助!

+0

你錯過了如何逐步執行代碼,看看裏面有什麼它發生:http://stackoverflow.com/questions/4929251/can-you-step-through-python-code-to-help-debug-issues或至少[printf調試](http://stackoverflow.com/questions/ 189562/what-is-proper-name-for-doing-debugging-by-adding-print-statements) – TessellatingHeckler

+0

@wwii同意。快速搜索顯示了很多可用於此問題的awnsers – FancyDolphin

+0

使用[Python中列出的[列出不規則列表]列表]的已接受答案(http://stackoverflow.com/questions/2158395/flatten-一個不規則的列表在Python中)迭代平展列表並檢查。 – wwii

回答

4
return inthere(thing,s) 

應該是:

if inthere(thing,s): 
    return True 

,然後把return False在函數的最末尾。現在不能正常工作的原因是,如果它找不到第一個嵌套列表中的東西,它不檢查其他東西。

+0

如果函數達到最後,它將隱式返回「無」,這是「虛假」。 –

+0

@KlausD。是的,但問題具體說明如果該項目不在列表中,它應該返回False,而不僅僅是任何falsy值。 –

1

可以打印thing那麼你知道爲什麼:

def inthere(ls, s): 
if s in ls: 
    return True 
else: 
    for thing in ls: 
     print thing 
     if isinstance(thing, list): 
      return inthere(thing,s) 

結果:

[2, 4] 
2 
4 
None 
[2, 4] 
True 

是的,你停止循環,因爲你在ls。你的第一個元素返回函數只是檢查整個列表和列表的第一個元素。您可以:

if inthere(thing, s): 
    return True 
0

第一個錯誤是你應該做的第一件事是檢查項目是否是一個列表。如果沒有,那麼你不會使用in,你會使用等於。

然後,如果是列表,請在列表中的每個項目上調用isthere。但是,除非獲得True響應,否則不應該返回循環,否則循環將在第一次迭代之後停止。有一個現成的功能來執行此快捷方式的行爲any

def inthere(i, s): 
    if isinstance(i, list): 
     return any(inthere(x, s) for x in i) 
    return i == s 

您還可以添加一個基本的測試來聲明返回的值是正確的。

B = {2, 4, 6, 8, 10, 12, 14, 16} 
for i in range(20): 
    assert inthere(A, i) == (i in B) 
0

我的建議會一直做這樣的事情:(但不知道你的要求是什麼)

def traverse(o, tree_types=(list, tuple)): 
    if isinstance(o, tree_types): 
     for value in o: 
      for subvalue in traverse(value, tree_types): 
       yield subvalue 
    else: 
     yield o 
#give a list of all values [2, 4, 6, 8, 10, 12, 14, 16] 

def inthere(ls,s): 
    if s in list(traverse(ls)): #check if your value is in that list 
     return True 
    else: 
     return False 


A=[[2,4],[6,[[[8],10]],12],14,16] 

print(inthere(A,12)) #return True 
print(inthere(A,2)) #Returns True