python - mptt 用于嵌套列表
我已经阅读了一些有关 mptt 解决方案的内容,并且正在尝试实现某种将嵌套列表转换为 mptt 列表的方法。我知道,在这种格式中它是无用的,但是可以使用子类或其他任何东西轻松更改嵌套列表。
我的代码是:
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 中的这种格式有时可能很有用,所以最好已经编写了一些代码。
I have read a little about mptt solution and I'm trying to implement some sort of translating a nested list into a mptt list. I know, that in this format it's useless, but nested lists can be easily changed with a classes childs or anything else.
The code I have is:
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
But the result is:
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
I see there is something not ok with the right value in recursion. I think such a format in python might be sometimes useful, so it would be nice to have some code for it already written.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通过添加全局迭代器已经解决了这个问题。
如果有人感兴趣,那就是新的 numerate 函数,它实际上工作得很好。
node()
不会改变。The problem has been solved by adding a global iterator.
If someone is interested, that's the new numerate function, which actually works fine.
The
node()
does not change.