Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 给定一个简单的(父、子)列表,创建一个分层字典树_Python_Python 3.x_Dictionary - Fatal编程技术网

Python 给定一个简单的(父、子)列表,创建一个分层字典树

Python 给定一个简单的(父、子)列表,创建一个分层字典树,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我有一个包含名称的元组列表。这些名称是父名称和子名称,我想用它们的名称创建一个分层字典树。 例如,我有以下列表: [('john','marry'),('mike','john'),('mike','hellen'),('john','elisa')] 我想创造这个: { 'mike':{ 'john':{ 'marry':{} 'elisa':{} } 'hellen':{}

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

[('john','marry'),('mike','john'),('mike','hellen'),('john','elisa')]
我想创造这个:

{
    'mike':{
        'john':{
            'marry':{}
            'elisa':{}
         }
         'hellen':{}
        }
}

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

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': {}}}}
无论如何,备选方案:

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)
结果:

{'mike': 
        {
         'hellen': {}, 
         'john': {
                  'elisa': {}, 
                  'marry': {}}}}

要归功于@WillemVanOnsem

如果有一个额外的元素,比如说
('elisa','mike')
,会发生什么?到目前为止,你尝试了什么?你具体被困在哪里?我认为这是错误的,因为迈克是约翰和海伦的父亲,约翰是伊莉莎的父亲。这意味着伊莉莎是迈克的孙子,不能是迈克的母亲。
('Elisa','mike')
如果伊莉莎的孩子名是迈克(新生儿),可能会发生我在求职面试中反驳了这个练习,但我无法解决它。这个练习和我贴的一模一样;我唯一能想到的就是找到祖父的名字,在这里是迈克;在那之后,我想不出什么东西来比较其余的名称..mapping dict正在自动更新,你能告诉我它是如何完成的示例:data=['B','A'],['C','B']]第一次迭代:mapping={'B':{},'A':{'B':{}}第二次迭代:parentitem={}在执行最后一行代码之后,我期望parentitem只更改parentitem={'C':{}}wiered behavious was映射也会自动更改,即使最后一行代码没有手动更新映射dict,这是如何工作的?映射dict是如何自动更改的?映射={'B':{'C':{},'A':{'B':{'C':{},'C':{}
{'mike': 
        {
         'hellen': {}, 
         'john': {
                  'elisa': {}, 
                  'marry': {}}}}