Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 递归地将列表切割为defaultdict树叶子_Python_Python 3.x - Fatal编程技术网

Python 递归地将列表切割为defaultdict树叶子

Python 递归地将列表切割为defaultdict树叶子,python,python-3.x,Python,Python 3.x,我在这里和其他地方都看到了这一点: import collections def Tree(): return collections.defaultdict(Tree) 我希望将值放入该树中,以便将值分组,以便 some_func(my_tree[0]) 可能被写入以返回我的_树[0][0]+我的_树[0][1] 这项工作: def subdivision_tree(pts): retval = Tree() def branch(pts, tree, keys=

我在这里和其他地方都看到了这一点:

import collections

def Tree():
    return collections.defaultdict(Tree)
我希望将值放入该树中,以便将值分组,以便

some_func(my_tree[0])
可能被写入以返回我的_树[0][0]+我的_树[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
...                }
...           }
...      }
... }

但我想我遗漏了一些明显的东西。有没有更清晰的方法来实现这一点?

更聪明的方法:

def branch(list_):
    if len(list_) == 1:
        return list_[0]
    else:
        return {
            0: branch(list_[:1]),
            1: branch(list_[1:])}
  • 返回一个更简单的字典 (仍然可以通过
    某些函数(dict[0])==>dict[0][0]+dict[0][1]
    重新组合)
  • 清晰的
  • fwiw,更优雅
  • 更像蟒蛇
您可能需要查看(没有使用经验)。