简体   繁体   English

如何在 python 中使用 BFS 创建树?

[英]How to create a tree using BFS in python?

So I have a flattened tree in JSON like this, as array of objects:所以我在 JSON 中有一个扁平树,就像这样,作为对象数组:

[{
    aid: "id3",
    data: ["id1", "id2"]
},

{
    aid: "id1",
    data: ["id3", "id2"]
},

{
    aid: "id2",
    nested_data: {aid: "id4", atype: "nested", data: ["id1", "id3"]},
    data: []
}]

I want to gather that tree and resolve ids into data with recursion loops into something like this (say we start from "id3" ):我想收集该树并将 id 解析为具有递归循环的数据,类似于这样(假设我们从"id3"开始):

{
   "aid":"id3",
   "payload":"1",
   "data":[
      {
         "id1":{
            "aid":"id1",
            "data":[
               {
                  "id3":null
               },
               {
                  "id2":null
               }
            ]
         }
      },
      {
         "id2":{
            "aid":"id2",
            "nested_data":{
               "aid":"id4",
               "atype":"nested",
               "data":[
                  {
                     "id1":null
                  },
                  {
                     "id3":null
                  }
               ]
            },
            "data":[
               
            ]
         }
      }
   ]
}

So that we would get breadth-first search and resolve some field into "value": "object with that field" on first entrance and "value": Null这样我们就可以进行广度优先搜索并将某些字段解析为"value": "object with that field""value": Null

How to do such a thing in python 3?如何在 python 3 中做这样的事情?

Apart from all the problems that your structure has in terms of syntax (identifiers must be within quotes, etc.), the code below will provide you with the requested answer.除了您的结构在语法方面存在的所有问题(标识符必须在引号内等)之外,下面的代码将为您提供所需的答案。

But you should carefully think about what you are doing, and have the following into account:但是你应该仔细考虑你在做什么,并考虑以下几点:

  • Using the relations expressed in the flat structure that you provide will mean that you will have an endless recursion since you have items that include other items that in turn include the first ones (like id3 including id1 , which in turn include id3 . So, you have to define stop criteria, or be sure that this does not occur in your flat structure.使用您提供的平面结构中表达的关系将意味着您将进行无休止的递归,因为您的项目包括其他项目,而其他项目又包括第一个项目(例如id3包括id1 ,而后者又包括id3 。所以,你必须定义停止标准,或者确保这不会发生在您的平面结构中。
  • Your initial flat structure is better to be in the form of a dictionary, instead of a list of pairs {id, data}.您的初始扁平结构最好采用字典的形式,而不是对 {id, data} 的列表。 That is why the first thing the code below does is to transform this.这就是为什么下面的代码要做的第一件事就是转换它。
  • Your final, desired structure contains a lot of redundancies in terms of information contained.您最终的所需结构在所包含的信息方面包含大量冗余。 Consider simplifying it.考虑简化它。
  • Finally, you mentioned nothing about the "nested_data" nodes, and how they should be treated.最后,您没有提及“nested_data”节点以及应如何处理它们。 I simply assumed that in case that exist, further expansion is required.我只是假设如果存在,则需要进一步扩展。

Please, consider trying to provide a bit of context in your questions, some real data examples (I believe the data provided is not real data, therefore the inconsistencies and redundancies), and try yourself and provide your efforts;请考虑尝试在您的问题中提供一些背景信息,一些真实数据示例(我相信提供的数据不是真实数据,因此存在不一致和冗余),并尝试自己并提供您的努力; that's the only way to learn.这是学习的唯一途径。

from pprint import pprint

def reformat_flat_info(flat):
    reformatted = {}
    for o in flat:
        key = o["aid"]
        del o["aid"]
        reformatted[key] = o
    return reformatted

def expand_data(aid, flat, lvl=0):
    obj = flat[aid]
    if obj is None: return {aid: obj}

    obj.update({"aid": aid})
    if lvl > 1:
        return {aid: None}

    for nid,id in enumerate(obj["data"]):
        obj["data"][nid] = expand_data(id, flat, lvl=lvl+1)

    if "nested_data" in obj:
        for nid,id in enumerate(obj["nested_data"]["data"]):
            obj["nested_data"]["data"][nid] = expand_data(id, flat, lvl=lvl+1)

    return {aid: obj}

# Provide the flat information structure
flat_info = [
    {
        "aid": "id3",
        "data": ["id1", "id2"]
    }, {
        "aid": "id1",
        "data": ["id3", "id2"]
    }, {
        "aid": "id2",
        "nested_data": {"aid": "id4", "atype": "nested", "data": ["id1", "id3"]},
        "data": []
    }
]
pprint(flat_info)
print('-'*80)

# Reformat the flat information structure
new_flat_info = reformat_flat_info(flat=flat_info)
pprint(new_flat_info)
print('-'*80)

# Generate the result
starting_id = "id3"
result = expand_data(aid=starting_id, flat=new_flat_info)
pprint(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM