以递归方式将列表剪切为defaultdict树叶

时间:2014-05-28 22:35:46

标签: python python-3.x

我在这里和其他地方看过这个:

import collections

def Tree():
    return collections.defaultdict(Tree)

我想将值放入该树中,以便将值分组,以便

some_func(my_tree[0])
可能会写

以返回my_tree [0] [0] + my_tree [0] [1]

这有效:

def subdivision_tree(pts):
    retval = Tree()
    def branch(pts, tree, keys=[0]):
        assert pts, "empty list sent to branch in subdivision_tree"
        if len(pts) == 1:
            for key in keys[:-1]:
                tree = tree[key]
            tree[keys[-1]] = pts[0]
        else:
            c = len(pts)//2
            branch(pts[:c], tree, keys=keys+[0])
            branch(pts[c:], tree, keys=keys+[1])
    branch(pts, retval)
    return retval

> subdivision_tree(list(range(5)))
"something like"
... {
...  0:
...      {
...       0:
...           {
...            0: 0,
...            1: 1
...           },
...       1:
...           {
...            0: 2,
...            1:
...                {
...                 0: 3,
...                 1: 4
...                }
...           }
...      }
... }

但我觉得我错过了一些明显的东西。是否有更清晰的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

更明智的方法:

def branch(list_):
    if len(list_) == 1:
        return list_[0]
    else:
        return {
            0: branch(list_[:1]),
            1: branch(list_[1:])}
  • 返回一个更简单的字典 (仍然可以通过some_func(dict_[0]) ==> dict_[0][0] + dict[0][1]重新分组)
  • 更明确
  • fwiw,更优雅。
  • 更多Pythonic?