如何将列表排序为层次结构父/子/孙?

时间:2017-05-15 13:13:10

标签: python html

将“a”列表排序为父/子层次结构。其中第一项是ID,第二项是说明,第三项是父ID。

a = [('222', 'Workroom', '111'),
('333', 'Setup Part', '222'),
('444', 'Scale', '222'),
('666', 'Workroom', '000'),
('888', 'Setup Part', '777'),
('777', 'Workroom', '666'),
('555', 'Workroom', '111'),
('111', 'Workroom', '000'),
('120', 'Workroom', '000'),
('100', 'Workroom', '000'),
('101', 'Workroom', '000'),
('110', 'Workroom', '101'),
('130', 'Workroom', '120')]

期望的输出

a = [('100', 'Workroom', '000'),
('101', 'Workroom', '000'),
    ('110', 'Workroom', '101'),
('111', 'Workroom', '000'),
    ('555', 'Workroom', '111'),
    ('222', 'Workroom', '111'),
        ('333', 'Setup Part', '222'),
        ('444', 'Scale', '222'),
('120', 'Workroom', '000'),
    ('130', 'Workroom', '120'),
('666', 'Workroom', '000'),
    ('777', 'Workroom', '666'),
        ('888', 'Setup Part', '777'),]

1 个答案:

答案 0 :(得分:0)

根据以下正确答案:

Python - Generate a dictionary(tree) from a list of tuples

您可以尝试:

a = [('222', 'Workroom', '111'),
('333', 'Setup Part', '222'),
('444', 'Scale', '222'),
('666', 'Workroom', '000'),
('888', 'Setup Part', '777'),
('777', 'Workroom', '666'),
('555', 'Workroom', '111'),
('111', 'Workroom', '000'),
('120', 'Workroom', '000'),
('100', 'Workroom', '000'),
('101', 'Workroom', '000'),
('110', 'Workroom', '101'),
('130', 'Workroom', '120')]

# step 1: create all the nodes dictionary
nodes = {}
for i in a:
    id, desc, parent_id = i
    nodes[id] = { 'id': id, 'desc': desc }

# step 2: create trees and parent-child relations
forest = []
for i in a:
    id, desc, parent_id = i
    node = nodes[id]

    # either make the node a new tree or link it to its parent
    if parent_id == '000':
        # start a new tree in the forest
        forest.append(node)
    else:
        # add new_node as child to parent
        parent = nodes[parent_id]
        if not 'children' in parent:
            # ensure parent has a 'children' field
            parent['children'] = []
        children = parent['children']
        children.append(node)

# step 3: simple function to print then with indentation
def print_node(node,level=0):
    print("  "*level, node['id'], node['desc'])
    if node.get('children',False):
        for child in node['children']:
            print_node(child,level=level+1)

for node in forest:
    print_node(node,level=0)

在答案中,我们为所有节点创建一个字典,然后为包含子节点的所有节点添加子值。

请注意,我不进行任何排序,只需创建林和节点并打印即可。如果需要,可以使用sorted函数进行排序。

告诉我这是不是你想要的。希望它有所帮助...