求助贴: 删除字典树的某些节点

2019-09-23 17:50:53 +08:00
 Kcelone

当前有这样一个树结构: 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

2433 次点击
所在节点    Python
4 条回复
Kcelone
2019-09-23 18:05:46 +08:00
好吧,刚才已经解决了,原来我之前只写了一半。。。0.0
Kcelone
2019-09-23 18:09:04 +08:00
不过,相对于递归,迭代的性能似乎更高些,我这算是抛转引玉了,如果能有迭代的方法可以解决,望不吝赐教。我把完整代码贴一下:import copy
def delete_node(mt):
mc = copy.deepcopy(mt)
for i in mc:
if i.get('work_page_id') not in xt:
mt.pop(mt.index(i))
elif i.get('children'):
delete_node(i.get('children'))
mm = copy.deepcopy(mc)
for i in mm:
if i.get('work_page_id') not in xt:
mc.pop(mc.index(i))
return mc
Kcelone
2019-09-23 18:10:20 +08:00
哈希树的问题日常还是比较常见的,多多积累。
Kcelone
2019-09-23 18:11:18 +08:00
补充:xt = ['6725', '6738', '6732', '6734']

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/603444

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX