简体   繁体   English

从字典创建列表列表

[英]Create a list of lists from dictionary

I have a dictionary as follows:我有一本字典如下:

d = {'a':['b','c'],'d':['c'],'e':['f'],'i':['g'],'g':['e'],'b':[],'c':[],'h':[],'f':[],}

where the keys represent each node and the values of each key represent their children.其中键代表每个节点,每个键的值代表它们的子节点。

I need an output as follows:我需要一个 output 如下:

[['a', 'd', 'i', 'h'], ['b', 'c', 'g'], ['e'], ['f']]
  • A list of lists, where the list1 has in-degree 0(level-0 nodes) and list2 has level-1 nodes, list3 has level-2 nodes and so on.. (Order of elements in the internal lists does not matter).列表的列表,其中 list1 具有度数 0(级别 0 节点),列表 2 具有级别 1 节点,列表 3 具有级别 2 节点,依此类推。(内部列表中元素的顺序无关紧要) .

  • There won't be any changes in the input dictionary.输入字典不会有任何变化。 But a parent can be declared later as another node's child as well, which has to be taken into consideration.(For example, here e is declared first as parent of f, but it later is declared as the child of g).但是父节点也可以稍后声明为另一个节点的子节点,这一点必须考虑在内。(例如,这里首先将 e 声明为 f 的父节点,但稍后将其声明为 g 的子节点)。

  • There won't be any duplicate entries of parents or keys.不会有任何重复的父母或钥匙条目。 Every node in the tree is declared only once as a single key.树中的每个节点仅被声明为一个键。 But there will be same values with different keys, depending on which parent they are linked to.但是不同的键会有相同的值,这取决于它们链接到哪个父级。

  • No cases of cycles in the dict.字典中没有循环的情况。

Could any of you please help me with the Python code for the same?你们中的任何人都可以帮助我使用相同的 Python 代码吗?

(I tried something similar to BFS algorithm but it's not giving me the desired output) (我尝试了类似于 BFS 算法的东西,但它没有给我想要的输出)

you can do this with two functions.你可以用两个函数来做到这一点。
this algorithm is not optimized, but it's possible for you to improve it:)此算法未优化,但您可以改进它:)

def append_value_at(l, value, index):
    # placing value in the index-th list of l. (lists are added if necessary)
    if len(l) <= index:
        l.append([ value ])
    else:
        if value not in l[index]:
            l[index].append(value)

    if len(l) == index:
        l.append([ ])

def convert_to_lists(d):
    returning = [ ]
    for key, values in d.items(): # iterate through the dictionary
        # finding index of the key
        node = 0
        for i in range(len(returning)):
            l = returning[i]
            for k in l:
                if k == key:
                    node = i

        append_value_at(returning, key, node)
        for val in values:
            append_value_at(returning, val, node + 1)

    return returning
d = {'a':['d'],'b':['d','e'],'c':['e','f'],'d':[],'e':['f'],'f':[]}
convert_to_lists(d)
>>> [['a', 'b', 'c'], ['d', 'e', 'f'], ['f']]

**note: ** your dictionary has a problem, f is a lvl 1 and 2 node... but it works anyway:) **注意:**您的字典有问题,f 是 lvl 1 和 2 节点...但它仍然可以工作:)
hope it helped !希望它有帮助!
kyros凯罗斯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM