-2

我正在 python 上开发基于树的程序。我需要使用递归重写此函数并清算所有这些 for 循环:

我的功能示例:

def items_on_level(full_tree, level):
    for key0, value0 in full_tree.items():
        for key1, value1 in value0.items():
            for key2, value2 in value1.items():
                for key3, value3 in value2.items():
                    print(key3)

输入:
- level - 我的递归树的级别
- full_tree - 带有父母和孩子的字典

{<Category: test>: {<Category: dkddk>: {}, <Category: test2>: {<Category: test3>: {}, <Category: test5>: {<Category: kfpokpok>: {}}}}

函数应该返回:当前级别的所有对象

帮助!谢谢!

4

4 回答 4

2
def itemsOnLevel(root, level):
  if not level:
    return list(root.keys())
  else:
    return list(itertools.chain.from_iterable([itemsOnLevel(v, level-1) for k,v in root.items()]))
于 2013-10-15T20:57:23.743 回答
1
itemsOnLevel = lambda r, l: (
    lambda f, r, l: f (f, r, l) ) (
    lambda f, r, l: [_ for _ in r.keys () ] if not l else
    [i for k in r.values () for i in f (f, k, l - 1) ], r, l)
于 2013-10-15T21:09:33.767 回答
0

我想这会有所帮助

if(full_tree != {}):

    for node in return_list_current_level(full_tree):
        items_on_level(node, level+1)
else:
    return None
于 2013-10-15T21:33:00.533 回答
0
def onl(r,l):
  if l:
    obj=[]
    for i in [onl(v,l-1) for v in r.values()]:
      obj.extend(i)
    return obj
  return r.keys()
于 2013-10-15T21:37:14.540 回答