Python 为什么我的递归函数返回;没有;?

Python 为什么我的递归函数返回;没有;?,python,recursion,dictionary,scope,Python,Recursion,Dictionary,Scope,全部, 我有一个Python字典列表的字典。这表示父子关系。如果有一个孩子,我想把父母还给我 这是我的收藏: tree = { u'one' : [ { u'two' : [ { u'three' : [] }, { u'four' : [] } ] }, { u'five' : [ { u'six' : [] } ] } ] } 如你所见,“一”有孩子“二”和“五”,“二”有孩子“三”和“四”,“三”没有孩子,依此类推 以下代码正确地计算出给定子级的父级: def find_parent(s

全部,

我有一个Python字典列表的字典。这表示父子关系。如果有一个孩子,我想把父母还给我

这是我的收藏:

tree = { u'one' : [ { u'two' : [ { u'three' : [] }, { u'four' : [] } ] }, { u'five' : [ { u'six' : [] } ] } ] }
如你所见,“一”有孩子“二”和“五”,“二”有孩子“三”和“四”,“三”没有孩子,依此类推

以下代码正确地计算出给定子级的父级:

def find_parent(search_term,collection,parent=None):
  if isinstance(collection,dict):
    for key,value in collection.iteritems():
      if key.lower() == search_term.lower():
        print "the parent of %s is %s" % (key,parent)
        return parent
      if isinstance(value,list):
        for v in value:
          find_parent(search_term,v,key)

my_child = "two"
my_parent = find_parent(my_child,tree)
该函数中的print语句始终打印正确的值。但如果我试图访问我的父母,它的值总是“无”。这里一定有什么东西超出了范围。我就是想不出怎么修理它

谢谢。

您可以递归调用
find\u parent(search\u term,v,key)
,但忽略返回的值。我建议您找到一个好的Python IDE,并学习使用它的调试功能。这将极大地帮助您跟踪这样的逻辑错误。

您还需要返回递归调用值:

if isinstance(value,list):
    for v in value:
        parent = find_parent(search_term,v,key)
        if parent is not None: return parent
如果没有
返回值
,则忽略、放弃递归搜索返回值

添加了
return
的演示:

>>> def find_parent(search_term,collection,parent=None):
...   if isinstance(collection,dict):
...     for key,value in collection.iteritems():
...       if key.lower() == search_term.lower():
...         print "the parent of %s is %s" % (key,parent)
...         return parent
...       if isinstance(value,list):
...         for v in value:
...           parent = find_parent(search_term,v,key)
...           if parent is not None: return parent
... 
>>> my_child = "two"
>>> tree = { u'one' : [ { u'two' : [ { u'three' : [] }, { u'four' : [] } ] }, { u'five' : [ { u'six' : [] } ] } ] }
>>> find_parent(my_child,tree)
the parent of two is one
u'one'

“find_parent”的递归调用中没有“return”。如果在第一次迭代中
return
,那么
for
循环有什么意义?