推荐学习书目
› 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
264768502
V2EX  ›  Python

如何进行子开关和主开关的逻辑优化

  •  
  •   264768502 · Sep 2, 2016 · 3329 views
    This topic created in 3714 days ago, the information mentioned may be changed or developed.

    以下代码 main_swit

    if kwarg.get('sub_switch'): 
        do()
        del kwarg['sub_switch']
    elif kwarg.get('sub_switch') is False:
        del kwarg['sub_switch']
    elif kwarg.get('sub_switch') is None and main_switch:
        do()
    

    这样的逻辑有没有可以优化的余地?

    6 replies  •  2016-09-10 12:45:25 +08:00
    BOYPT
    BOYPT
    Sep 2, 2016
    1
    写到这样的逻辑都会想哭
    Allianzcortex
    Allianzcortex
    Sep 2, 2016
    2
    if 'sub_switch' in kwarg:
    kwarg.pop()

    这样子的。。。??
    264768502
    264768502
    OP
    Sep 2, 2016 via Android
    3
    或许这样更好
    ```python
    try:
    if kwarg.pop('sub_switch'):
    do()
    except KeyError:
    if main_switch:
    do()
    ```
    just4test
    just4test
    Sep 5, 2016
    4
    首先你不能
    temp = kwarg.get('sub_switch')
    么?
    264768502
    264768502
    OP
    Sep 5, 2016
    5
    @just4test 可以赋值先,不过逻辑判断的过程依然很丑陋
    264768502
    264768502
    OP
    Sep 10, 2016 via Android
    6
    果然抛开业务谈逻辑不是很好,这里还有个性能问题
    查了一下,当 key 高概率在字典,可以用 try.否则先查看有没有,再执行逻辑,性能上会更好
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5008 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 07:05 · PVG 15:05 · LAX 23:05 · JFK 02:05
    ♥ Do have faith in what you're doing.