【发布时间】:2015-11-16 18:07:01
【问题描述】:
我有一个 [node_id, name, parent_node_id] 格式的数据集。我想输出一个缩进的节点树。我已经能够做第一代,但不知道如何继续迭代列表。我不得不使用 try/except 子句,因为并非所有子列表都会附加它们的生成,因为我无法继续循环。
Grandparent
Parent 1
Parent 2
Child 1
Child 2
代码:
# establish data set in the format of [node_id, name, parent_node_id]
tree_info = [['5', 'Child 2', '3'],
['1', 'Grandparent', 'root'],
['4', 'Child 1', '3'],
['3', 'Parent 2', '1'],
['2', 'Parent 1', '1']
]
# establish root node
root = [x[0] for x in tree_info if x[2] == 'root'][0]
# assign root node a generation of 0
tree_info[0].append(0)
# loop through
for node in tree_info:
node_id = node[0]
node_parent_id = node[2]
if node_parent_id == root:
# assign a generation of 1
node.append(1)
for node in tree_info:
try:
print node[3] * " ", node[2]
except:
print "help"
【问题讨论】:
-
您的数据结构使这变得很棘手,因为正如所写的那样,确定您应该使用什么级别的缩进是不切实际的。如果你需要一个树形结构,就做一个树形结构,不要尝试使用平面数据结构和命令式代码来执行更明显可以用嵌套数据结构和递归代码解决的任务。
-
@felipsmartins:基本思想类似,但这段代码实际上并没有使用真正的节点,它试图将树状关系破解成非树状代码。
-
OP,与其尝试使用当前数据结构进行打印的逻辑,我建议尝试将您拥有的内容转换为更实用的数据结构列表嵌套的列表或其他内容。
-
@RNar - 同意,把它分成两个问题:(1)将
tree_info解析成你想要的嵌套结构,然后(2)打印出这个结构的结果
标签: python python-2.7