如何生成BOM表结构?

时间:2019-07-13 02:10:37

标签: python python-3.x

我有一个像这样的数组:

array = ['aa:0','bb:1', 'cc_a:2', 'cc_a:2', 
      'cc_b:2', 'cc_b:2', 'cc_b:2', 
      'cc_b:2', 'cc_c:2', 'cc_c:2', 
      'cc_c:2', 'cc_c:2', 'cc_d:2', 
      'dd_a:3', 'dd_a:3', 'dd_a:3', 
      'cc_c:3', 'ee:3','cc_d:2', 
      'dd_a:3', 'dd_a:3', 'dd_a:3', 
      'cc_c:3', 'ee:2','dd_a:3', 'dd_a:3', 'dd_a:3']

要打印为:

"""
aa:0x1
**bb:1x1
****cc_a:2x2
****cc_b:2x4
****cc_c:2x4
****cc_d:2x2
******dd_a:3x3
******cc_c:3x1
****ee:2x1
******dd_a:3x3
"""

cc_a:2x2 cc_a是数字,2是深度,x2是数量

我已经用python建立了一棵树,但是有一个计算数量的想法。

array = ['aa:0','bb:1', 'cc_a:2', 'cc_a:2', 
      'cc_b:2', 'cc_b:2', 'cc_b:2', 
      'cc_b:2', 'cc_c:2', 'cc_c:2', 
      'cc_c:2', 'cc_c:2', 'cc_d:2', 
      'dd_a:3', 'dd_a:3', 'dd_a:3', 
      'cc_c:3', 'ee:3','cc_d:2', 
      'dd_a:3', 'dd_a:3', 'dd_a:3', 
      'cc_c:3', 'ee:2','dd_a:3', 'dd_a:3', 'dd_a:3']

class TreeNode(object):
    def __init__(self,name):
        self.name = name
        self.children = []

def build_tree(arr):
    root_node = None
    counter = collections.defaultdict(list)
    for item in arr:
        name,depth = item.strip().split(':')
        if depth == '0':
            root_node = TreeNode(name)
            counter[depth].append(root_node)
        else:
            father = counter[str(int(depth)-1)][-1]
            child = TreeNode(name)
            father.children.append(child)
            counter[depth].append(child)   
    return root_node

tree = build_tree(array)

def dfs(node,depth):
    if not node:
        return
    print ("**"*depth+node.name)
    for c in node.children:
        dfs(c,depth+1)          
dfs(tree,0)

print:
aa
**bb
****cc_a
****cc_a
****cc_b
****cc_b
****cc_b
****cc_b
****cc_c
****cc_c
****cc_c
****cc_c
****cc_d
******dd_a
******dd_a
******dd_a
******cc_c
******ee
****cc_d
******dd_a
******dd_a
******dd_a
******cc_c
****ee
******dd_a
******dd_a
******dd_a

want to print like:
aa:0x1
**bb:1x1
****cc_a:2x2
****cc_b:2x4
****cc_c:2x4
****cc_d:2x2
******dd_a:3x3
******cc_c:3x1
****ee:2x1
******dd_a:3x3

1 个答案:

答案 0 :(得分:0)

这不是答案,更多的是评论,而不是答案。 您谈论的是具有父/子结构的树。
但是在数组中,我看不到父子关系!!!
您能否更清楚地说明如何在数组中创建父/子结构?