我想写一个递归函数,如果元素在嵌套列表中,它将返回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.
我确实失去了一些东西,我似乎无法告诉,我感谢所有帮助!
你错过了如何逐步执行代码,看看里面有什么它发生: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
@wwii同意。快速搜索显示了很多可用于此问题的awnsers – FancyDolphin
使用[Python中列出的[列出不规则列表]列表]的已接受答案(http://stackoverflow.com/questions/2158395/flatten-一个不规则的列表在Python中)迭代平展列表并检查。 – wwii