Recursively creating a tree hierarchy without using class/object

前端 未结 1 725
一整个雨季
一整个雨季 2021-01-24 00:10

I am having trouble creating a tree hierarchy in Python 3. I\'d like to be able to do this without using classes.

The data I need to start with is not in order and in th

相关标签:
1条回答
  • 2021-01-24 00:31

    You can simply iterate over every child,parent tuple, create dictionary that maps the id's of the child and the parent to a list that contains the children of these elements. We keep doing this until we are done.

    roots = set()
    mapping = {}
    for child,parent in data:
        childitem = mapping.get(child,None)
        if childitem is None:
            childitem =  {}
            mapping[child] = childitem
        else:
            roots.discard(child)
        parentitem = mapping.get(parent,None)
        if parentitem is None:
            mapping[parent] = {child:childitem}
            roots.add(parent)
        else:
            parentitem[child] = childitem
    

    Now that we have done that, roots is a set of the ids of the tree roots: so for each such element we know that there is no id that is a parent. For each id in the roots, we can simply fetch from the mapping and that is a dictionary of the structure {'childid':child} where childid is the id (here a string) and child is again a dictionary of that form.

    So you can print them like:

    for root in roots:
        print(mapping[root])
    

    So in your case, the tree is:

    tree = { id : mapping[id] for id in roots }
    

    For your sample data, it generates:

    >>> tree
    {'R1': {'P1': {'C1': {'E1': {}}}, 'P2': {'C2': {'E2': {}}, 'C3': {}}}, 'R2': {'P4': {'C6': {'E4': {}}}, 'P3': {'C5': {}, 'C4': {'E3': {}}}}, 'R3': {'P6': {'C8': {}, 'C9': {'E6': {}}}, 'P5': {'C7': {'E5': {}}}}, 'R4': {'P8': {'C12': {'E8': {}}}, 'P7': {'C11': {}, 'C10': {'E7': {}}}}}
    
    0 讨论(0)
提交回复
热议问题