我在这里和其他地方看过这个:
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
... }
... }
... }
... }
但我觉得我错过了一些明显的东西。是否有更清晰的方法来实现这一目标?
答案 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]
重新分组)