需要在python

问题描述

我是编程新手,真的不知道如何表达我的问题,所以代码如下:

mapping_dict = {
    0: [1,2,3,4,5,6],1: [7,8,9],2: [10,11,12],3: [],4: [],5: [],6: [],7: [13,14],8: [],9: [],10: [],11: [],12: [],13: [],14: []
}
proper_id_list = []

mapping_dict中的键和值也可以是字符串。我需要这样的东西:

proper_id_list = [0,1,7,13,14,9,10,12,6]

这里发生的事情是每个列表必须在其键之后立即添加

到目前为止,我能想到的代码如下:

for a in mapping_dict[0]:
    proper_id_list.append(a)
    for a in mapping_dict[0]:
        proper_id_list.append(a)
        for a in mapping_dict[0]:
            proper_id_list.append(a)  # ... this will keep repeating,God kNows how many times

我已经对这些循环进行了20次硬编码,并且可以正常工作,但是我知道这是一个糟糕的设计,限制为20个级别,mapping_dict中的顶级密钥必须为0。

我希望这是有道理的。请帮忙!

解决方法

您实际上只需要一个循环。从最低的键开始,对键进行排序,在列表中找到它们,然后插入它们各自的值。

proper_id = [min(mapping_dict)]
for k in sorted(mapping_dict):
    i = proper_id.index(k)
    proper_id[i+1:i+1] = mapping_dict[k]

print(proper_id)
# -> [0,1,7,13,14,8,9,2,10,11,12,3,4,5,6]

但是,基于有关深度优先搜索的评论,我可能会遗漏了这一点。这可能不能一概而论,或者对于大型数据集来说可能很慢,因为它是O(n ** 2)。