Python 有条件循环遍历

有个场景需要通过传入的列表遍历一个列表里每个字典并判断特定键值是否在允许的列表里.
通过迭代和计数来实现节点判断和遍历.
以下是实现方法

info = [
    {'title': 'a', 'children': [{'title': 'a-1', 'children': []}]},
    {'title': 'b', 'children': [
        {'title': 'b-1', 'children': [
            {'title': 'b-1-1', 'children': []},
            {'title': 'b-1-2', 'children': []}
        ]}
    ]},
    {'title': 'c', 'children': []},
    {'title': 'd', 'children': [
        {'title': 'd-1', 'children': [
            {'title': 'd-1-1', 'children': []},
            {'title': 'd-1-2', 'children': []}
        ]},
        {'title': 'd-2', 'children': []}
    ]},
    {'title': 'e', 'children': []},
]

def get_allow(info_in, allow_in):
    result_to_return = []
    success_status, allow_count = False, 0
    for i in info_in:
        if not i.get('children'):
            '进入根节点'
            print(f"root --- {i.get('title')}")
            if i.get('title') not in allow_in:
                continue
            else:
                allow_count += 1
        i2 = {
            'title': i.get('title'),
            'children': []
        }
        
        if i.get('children'):
            '不是根节点, 迭代检查, 并获取子节点返回回来的状态'
            children, success_status = get_allow(i.get('children'), allow_in)
            if success_status:
                '存在任一子节点在允许清单'
                result_to_return.append(i2)
                result_to_return[result_to_return.index(i2)]['children'] = children
        elif allow_count:
            '是根节点, 并且在允许清单里!'
            result_to_return.append(i2)
    if success_status:
        pass
    elif allow_count > 0 and not success_status:
        '根节点在清单中, 修改状态'
        success_status = True
    return result_to_return, success_status
allow_list = ['d-1-2', 'e']
print(get_allow(info, allow_list))

结果:

root --- a-1
root --- b-1-1
root --- b-1-2
root --- c
root --- d-1-1
root --- d-1-2
root --- d-2
root --- e
([{'children': [{'children': [{'children': [], 'title': 'd-1-2'}],
                 'title': 'd-1'}],
   'title': 'd'},
  {'children': [], 'title': 'e'}],
 True)
posted @ 2021-11-24 11:13  nextkara  阅读(195)  评论(0编辑  收藏  举报