首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >给定一个平面列表(父、子),创建一个层次字典树

给定一个平面列表(父、子),创建一个层次字典树
EN

Stack Overflow用户
提问于 2017-08-02 12:16:07
回答 3查看 9K关注 0票数 3

我有一个包含名字的元组的列表。这些名称是父名和子名,我希望用它们的名称创建层次字典树。例如,我有以下列表:

代码语言:javascript
复制
[('john','marry'),('mike','john'),('mike','hellen'),('john','elisa')]

我想要创造这个:

代码语言:javascript
复制
{
    'mike':{
        'john':{
            'marry':{}
            'elisa':{}
         }
         'hellen':{}
        }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-08-02 12:54:36

假设它表现良好(没有循环,没有重复的名字,或者一个孩子有多个父母),你可以简单地使用一个“有向图”并遍历它。要查找根,我还使用了一个包含布尔值的字典,该字典指示名称是否有父级:

代码语言:javascript
复制
lst = [('john','marry'), ('mike','john'), ('mike','hellen'), ('john','elisa')]

# Build a directed graph and a list of all names that have no parent
graph = {name: set() for tup in lst for name in tup}
has_parent = {name: False for tup in lst for name in tup}
for parent, child in lst:
    graph[parent].add(child)
    has_parent[child] = True

# All names that have absolutely no parent:
roots = [name for name, parents in has_parent.items() if not parents]

# traversal of the graph (doesn't care about duplicates and cycles)
def traverse(hierarchy, graph, names):
    for name in names:
        hierarchy[name] = traverse({}, graph, graph[name])
    return hierarchy

traverse({}, graph, roots)
# {'mike': {'hellen': {}, 'john': {'elisa': {}, 'marry': {}}}}
票数 12
EN

Stack Overflow用户

发布于 2017-08-02 13:55:38

不管怎样,还有其他选择:

代码语言:javascript
复制
data = [('john','marry'),('mike','john'),('mike','hellen'),('john','elisa')]

roots = set()
mapping = {}
for parent,child 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

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

print (tree)

结果:

代码语言:javascript
复制
{'mike': 
        {
         'hellen': {}, 
         'john': {
                  'elisa': {}, 
                  'marry': {}}}}

@WillemVanOnsem Recursively creating a tree hierarchy without using class/object信用卡

票数 2
EN

Stack Overflow用户

发布于 2017-08-02 13:11:21

代码语言:javascript
复制
def get_children(parent, relations):
    children = (r[1] for r in relations if r[0] == parent)
    return {c: get_children(c, relations) for c in children}

the_list = [('john','marry'),('mike','john'),('mike','hellen'),('john','elisa')]

parents, children = map(set, zip(*the_list))
the_tree = {p: get_children(p, the_list) for p in (parents - children)}

print(the_tree)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45460653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档