python-mptt用于嵌套列表
我已经读了一些关于mptt解决方案的书,我正在尝试实现某种将嵌套列表转换成mptt列表的方法。我知道,在这种格式下它是无用的,但是嵌套列表可以很容易地用类childs或其他任何东西来更改 我的密码是:python-mptt用于嵌套列表,python,recursion,mptt,Python,Recursion,Mptt,我已经读了一些关于mptt解决方案的书,我正在尝试实现某种将嵌套列表转换成mptt列表的方法。我知道,在这种格式下它是无用的,但是嵌套列表可以很容易地用类childs或其他任何东西来更改 我的密码是: tree = [[1,[[11,[111, 112, 113]],[12,]]],[2,[[21,[[211,[2111,]],]],]]] class node(): def __init__(self, value, lft): self.value = value
tree = [[1,[[11,[111, 112, 113]],[12,]]],[2,[[21,[[211,[2111,]],]],]]]
class node():
def __init__(self, value, lft):
self.value = value
self.lft = lft
def add_right(self, rgt):
self.rgt = rgt
def __str__(self):
return "%s | %s | %s" %(self.value, self.lft, self.rgt)
def numerate(table, tree, counter):
for item in tree:
if type(item) == type(1):
table.append(node(item, counter))
index = len(table)
counter += 1
else:
table.append(node(item[0], counter))
index = len(table)
counter += 1
if len(item) > 1:
(table, counter) = numerate(table, item[1], counter)
table[index-1].add_right(counter)
return (table, counter)
table = numerate([], tree, 0)[0]
for item in table:
print item
但结果是:
1 | 0 | 6
11 | 1 | 5
111 | 2 | 3
112 | 3 | 4
113 | 4 | 5
12 | 5 | 6
2 | 6 | 10
21 | 7 | 10
211 | 8 | 10
2111 | 9 | 10
我发现递归中的正确值有问题。我认为python中的这种格式有时可能很有用,因此最好已经为它编写了一些代码。通过添加一个全局迭代器,问题已经得到了解决 如果有人感兴趣,那就是新的计算函数,它实际上工作得很好
global_iterator = 0
def numerate(table, tree):
global global_iterator
for item in tree:
global_iterator += 1
if type(item) == type(1):
table.append(node(item, global_iterator))
index = len(table)
else:
table.append(node(item[0], global_iterator))
index = len(table)
if len(item) > 1:
table.append(numerate(table, item[1]))
global_iterator += 1
table[index-1].add_right(global_iterator)
return table
table = numerate([], tree)
节点()
不会更改