2017-02-24 98 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