【问题标题】:How to find the deepest dict-level of a multilevel python dict? [duplicate]如何找到多级 python dict 的最深 dict 级别? [复制]
【发布时间】:2014-12-02 13:00:06
【问题描述】:

例如,如果我们有一个像{a: {b: c}, d: e} 这样的字典,那么这个字典的最大级别是 2。

我这两天一直在想找到任意dict的最大级别的方法,但没有找到解决方案。

怎么做?

【问题讨论】:

  • 所以你在这里寻找一个整数?你想解决什么问题?
  • @MartijnPieters,是的,我正在尝试用字典树的表示来解决八皇后难题。比如,result={(1,2):{(3.4):{...}}},所以如果结果的子项的深度为 8,那么它就是解决方案之一。

标签: python algorithm dictionary


【解决方案1】:

使用递归:

def nested_depth(d):
    if not isinstance(d, dict):
        return 0
    if not d:
        return 1
    return 1 + max(nested_depth(v) for v in d.values())

【讨论】:

  • 是的,我知道我应该在这里使用递归,但是在处理这个问题时,我的头脑完全是一团糟。谢谢,我会仔细研究你的答案。
猜你喜欢
  • 1970-01-01
  • 2021-10-11
  • 2018-01-10
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 2011-07-03
相关资源
最近更新 更多