当前有这样一个树结构: mtt = [ {'wp_id': '6725','children': [ {'wp_id': '6739'}, {'wp_id': '6737'} ] }, {'wp_id': '6738'}, {'wp_id': '6734', 'children': [{'wp_id': '6732'}, {'wp_id': '6733'}] } ] 删除其中 wp_id 不在['6725', '6738', '6732', '6734']中的其他节点。 要求: 某一节点不符合要求,则其所有子节点均视为不合要求,可直接删除。
自己写了个递归处理,发现不能满足所有情况,求助算法大牛了。
def delete_node(mt): mc = copy.deepcopy(mt) for i in mc: if i.get('wp_id') not in xt: mt.pop(mt.index(i)) elif i.get('children'): delete_node(i.get('children')) mt = mc return mt