使用递归获取所有树子项

时间:2019-07-03 09:18:00

标签: python python-3.x

我彼此之间有一棵树,我想要当我选择一片叶子时按顺序排列所有子项。

例如,我有产品A,其子产品B&C和产品B有其他2个产品D,E,产品C有3个产品F&G&S,产品D有2个产品H,I

所以当我选择产品A时,我需要编号子树

1.A
1.1.B
1.1.1.D
1.1.1.1.H
1.1.1.2.I
1.1.2.E
1.2.C
1.2.1.F
1.2.2.G
1.2.3.S

我试图通过递归来解决此问题,但编号仍然存在问题。 这是我尝试过的:

PRODUCT_LIST = []
class MyClass(object):
    PRODUCT_LEVEL=0

    def _get_sub_levels(self, product_id, level='1'):
        new_level = 1
        # product_accessory_ids is product sub products
        for item in product_id.product_accessory_ids:
            level = level + '.' + str(new_level)
            PRODUCT_LIST.append(
                {'level': level, 'products': item})
            if item.product_id.product_tmpl_id.product_accessory_ids:
                new_level += 1

                self._get_sub_levels(item.product_id.product_tmpl_id, level=level)
            else:
                PRODUCT_LIST.append(
                    {'level': level, 'products': product_id.product_accessory_ids})
        else:
            PRODUCT_LIST.append(
                {'level': level, 'products': product_id.product_accessory_ids})
            # new_level+=1
            # level = level +'.'+ str(new_level)
            # PRODUCT_LIST.append(
            #     {'level': level, 'products': product_id.product_accessory_ids})
            # if item.product_id.product_tmpl_id.product_accessory_ids:
            #     new_level = '.1'
            #     level = level + new_level
            #     self._get_sub_levels(item.product_id.product_tmpl_id, level=level)
        return PRODUCT_LIST

    product_list = _get_sub_levels(product_id, str(PRODUCT_LEVEL))

2 个答案:

答案 0 :(得分:1)

我解决了我的问题..这是解决方法:

首先我得到第一个产品A的级别,如果它在选择中是1,2 ..然后我将其传递给_get_sub_levels:


    def _get_sub_levels(self, product_id):
        accessories = product_id.product_accessory_ids
        product_list = []
        depth = [1]

        def wrapped(product_id):
            depthStr = '.'.join([str(i) for i in depth])
            product_list.append(
                {'level': depthStr, 'products': [product_id]})

            depth.append(1)
            for child in product_id.product_id.product_tmpl_id.product_accessory_ids:
                wrapped(child)
                depth[-1] += 1
            depth.pop()

        for accessory in accessories:
            wrapped(accessory)
            depth[0] += 1
        return product_list

答案 1 :(得分:0)

一个简单的递归就足够了。

例如:

def _get_sub_levels(self, product_id, prefix="1"):
    result = [ {"level":prefix, "product":product_id} ]
    for i,accessory in enumerate(product_id.product_accessory_ids,1):
        result += self._get_sub_levels(accessory,f"{prefix}.{i}")
    return result