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,更优雅
- 更像蟒蛇