推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
Kcelone
V2EX  ›  Python

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

  •  
  •   Kcelone · Sep 23, 2019 · 3490 views
    This topic created in 2565 days ago, the information mentioned may be changed or developed.

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

    4 replies  •  2019-09-23 18:11:18 +08:00
    Kcelone
        1
    Kcelone  
    OP
       Sep 23, 2019
    好吧,刚才已经解决了,原来我之前只写了一半。。。0.0
    Kcelone
        2
    Kcelone  
    OP
       Sep 23, 2019
    不过,相对于递归,迭代的性能似乎更高些,我这算是抛转引玉了,如果能有迭代的方法可以解决,望不吝赐教。我把完整代码贴一下: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
        3
    Kcelone  
    OP
       Sep 23, 2019
    哈希树的问题日常还是比较常见的,多多积累。
    Kcelone
        4
    Kcelone  
    OP
       Sep 23, 2019
    补充:xt = ['6725', '6738', '6732', '6734']
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2468 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 12:26 · PVG 20:26 · LAX 05:26 · JFK 08:26
    ♥ Do have faith in what you're doing.