Python-动态构建嵌套树

时间:2018-11-27 16:05:57

标签: python json algorithm recursion tree

我正在尝试使用python构建树层次结构,可以说我有他的结构,我需要能够向Bannana中动态添加更多子级。 我想我的问题还不清楚

更新:我需要创建一个这样的结构,但是值会发生变化,因此我需要创建函数以传递int并创建该数量的Apple(Children)并执行柠檬和所有其他孩子也是一样。苹果节点也是根节点。

Apple
   Bannana
   Lemon
      Juice
        Drink
   Watermelon
       Red
         Round

但是然后我可以拥有一个完全不同的结构,例如

Apple
   Bannana
   Lemon
      Juice
        Drink
          Watermelon
       Red
          Round

Json Ouptut应该是

{
    'Apple': 'Fruit',
    'children': [{
        'Bannana': 'fruit',
        'children': None
    },  {
        'Lemon': 'Fruit',
        'children': [{
            'Juice': 'Food',
            'children': [{
                'Drink': 'Action',
                'children': None
             And so on...

如何使层次结构动态化?例如特定父项下的行数?

我从发现的示例中尝试了类似的方法

import collections
def add_element(root, path, data):
    if len(path) == 1:
        root[path[0]] = data
    else:
        add_element(root[path[0]], path[1:], data)

count = 1


tree = lambda: collections.defaultdict(tree)
root = tree()
n= 10
for i in range(1,n):
    path_list= ['Apple', 'Lemon', 'Juice' + str(count)]
    print (path_list)
    count += 1
    add_element(root,path_list, 1 )
print (root)

编辑1

根据答案,我对代码进行了一些修改

args = {'Apple': 'Apple', 'Lemon': 'Lemon', 'Juice': 'Juice', 'Drink': 'Drink'}

s = """
{Apple}
   {Lemon}
      {Juice}
         {Drink}
""".format(**args)

def group_data(vals):
  if len(vals) == 1:
     return {vals[0]:'Fruit', 'Children':None}
  new_data = [list(b) for _, b in itertools.groupby(vals, key=lambda x:bool(re.findall('^\s', x)))]
  new_group = [[new_data[i], new_data[i+1]] for i in range(0, len(new_data), 2)]
  result = []
  for a, b in new_group:
     result.extend([{i:'Fruit', 'Children':None} for i in a[:-1]])
     result.append({a[-1]:'Fruit', 'Children':group_data([re.sub('^\s{3}', '', c) for c in b])})
  return result

_new_data = [i.strip('\n') for i in filter(None, s.split('\n'))]


print(json.dumps(group_data(_new_data), indent=4))

这可以很好地工作,但是它仍然是硬编码的,这不是我想要的。

1 个答案:

答案 0 :(得分:1)

您可以分析每个水果之前的空白:

s = """
Apple
   Bannana
   Lemon
      Juice
         Drink
            Watermelon
      Red
         Round
"""

import itertools, re
def group_data(vals):
  if len(vals) == 1:
     return {vals[0]:'Fruit', 'Children':None}
  new_data = [list(b) for _, b in itertools.groupby(vals, key=lambda x:bool(re.findall('^\s', x)))]
  new_group = [[new_data[i], new_data[i+1]] for i in range(0, len(new_data), 2)]
  result = []
  for a, b in new_group:
     result.extend([{i:'Fruit', 'Children':None} for i in a[:-1]])
     result.append({a[-1]:'Fruit', 'Children':group_data([re.sub('^\s{3}', '', c) for c in b])})
  return result

_new_data = [i.strip('\n') for i in filter(None, s.split('\n'))]

import json
print(json.dumps(group_data(_new_data), indent=4))

输出:

[
     {
       "Apple": "Fruit",
       "Children": [
         {
            "Bannana": "Fruit",
            "Children": null
           },
           {
               "Lemon": "Fruit",
               "Children": [
                  {
                      "Juice": "Fruit",
                       "Children": [
                            {
                             "Drink": "Fruit",
                             "Children": {
                                 "Watermelon": "Fruit",
                                 "Children": null
                              }
                          }
                      ]
                  },
                  {
                       "Red": "Fruit",
                       "Children": {
                          "Round": "Fruit",
                          "Children": null
                     }
                  }
              ]
          }
       ]
    }
]