【问题标题】:Need to repeat the same loop within each loop an unknown number of times in python需要在每个循环中在 python 中重复相同的循环未知次数
【发布时间】: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 所说,查看如何进行深度优先树遍历。
  • 例如见this question

标签: python python-3.x loops recursion


【解决方案1】:

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

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]

但是,根据有关深度优先搜索的 cmets,我可能会忽略这一点。这可能无法概括,或者对于大型数据集可能非常慢,因为它是 O(n**2)。

【讨论】:

  • 数据集永远不会太大。极端情况下为 5000 项。但是,无法对键进行排序。这些实际上是数据库中行的 ID,它们的顺序可以更改。 1 不一定比 2 高,反之亦然。
猜你喜欢
  • 1970-01-01
  • 2014-01-02
  • 2020-07-18
  • 1970-01-01
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
相关资源
最近更新 更多