【发布时间】:2020-12-03 18:43:59
【问题描述】:
我是编程新手,真的不知道如何表达我的问题,所以这里是代码:
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,8,9,2,10,11,12,3,4,5,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。
我希望这是有道理的。请帮忙!
【问题讨论】:
-
这是深度优先搜索。谷歌它的算法。
-
您正在遍历树结构。正如@Barmar 所说,查看如何进行深度优先树遍历。
标签: python python-3.x loops recursion