【问题标题】:Traversing through a tree (multi nest)遍历一棵树(多巢)
【发布时间】:2020-12-06 23:22:09
【问题描述】:

如果嵌套最多 10 个级别,每个级别具有不同的长度,则存在父级、子级、孙子级和更多关系,如下面给出的 json (id 在每个列表中是唯一的)。找到uni_code 以将另一个对象(子对象)插入其列表的最佳方法是什么?

{
  "id": "1",
  "status": "active",
  "created": "",
  "children": [{
      "id": "1",
      "status": "active",
      "created": "",
      "children": [{
          "id": "1",
          "status": "active",
          "created": "",
          "children": [{
              "id": "1",
              "status": "active",
              "created": "",
              "children": [

              ],
              "uni_code": "EGCFJ1"
            },
            {
              "id": "1",
              "status": "active",
              "created": "",
              "children": [

              ],
              "uni_code": "D356RY"
            },

          ],
          "uni_code": "EGCFJ1"
        },


      ],
      "uni_code": "Y7TUP8"
    },


    {
      "id": "4",
      "status": "active",
      "created": "",
      "children": [

      ],
      "uni_code": "WA1JNS"
    },


         ],
  "uni_code": "I429TD"
}

【问题讨论】:

  • 你已经尝试了什么,你的想法是什么?
  • 一个选项是循环遍历每个级别的所有元素。
  • @martineau 的解决方案工作

标签: python json for-loop recursion arraylist


【解决方案1】:

根据您在评论中提出的后续问题,我相信我现在明白了您的要求……并相应地更新了我的答案。

您通常可以使用递归调用自身的函数来遍历递归数据结构(如树)。

我的意思:

def insert_into_tree(tree, new_child, target):
    if tree['uni_code'] == target:
        tree['children'].append(new_child)
        return True
    for child in tree['children']:
        if insert_into_tree(child, new_child, target):
            return True
    return False  # `target` not found.


data = {
    "id": "1",
    "status": "active",
    "created": "",
    "children": [
        {
            "id": "1",
            "status": "active",
            "created": "",
            "children": [
                {
                    "id": "1",
                    "status": "active",
                    "created": "",
                    "children": [
                        {
                            "id": "1",
                            "status": "active",
                            "created": "",
                            "children": [],
                            "uni_code": "EGCFJ1"
                        },
                        {
                            "id": "1",
                            "status": "active",
                            "created": "",
                            "children": [],
                            "uni_code": "D356RY"
                        }
                    ],
                    "uni_code": "EGCFJ1"
                }
            ],
            "uni_code": "Y7TUP8"
        },
        {
            "id": "4",
            "status": "active",
            "created": "",
            "children": [],
            "uni_code": "WA1JNS"
        }
    ],
    "uni_code": "I429TD"
}


new_object = {
    "id": "1",
    "status": "active",
    "created": "",
    "children": [],
    "uni_code": "THX1138"
}

target = "EGCFJ1"
if insert_into_tree(data, new_object, target):
    print(f'new child added to {target!r}')
else:
    print(f'{target!r} not found, new child not added')

【讨论】:

  • 有没有办法使用上述函数在任何 uni_code 中创建一个新子代?
  • 我的用例很简单,我使用的是带有 Postgres(JSONField) 的 Django,我需要为所有对象维护一个树,并在创建新子时更新它或在子时删除它已移除。所以,每次我添加一个新孩子时,我都需要一棵更新了新孩子的整棵树。如果我使用上面的函数,它只会给孩子和它的直接父母,而不是整个树。有什么解决办法吗?
  • 如果您在调用我的答案中当前显示的insert_into_tree() 之后添加import json 后跟print(json.dumps(data, indent=4)),您会看到它实际上更新了整个树。
猜你喜欢
  • 2011-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
相关资源
最近更新 更多