推荐学习书目
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 · 2913 views
    This topic created in 3545 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
        1
    BOYPT  
       Sep 2, 2016
    写到这样的逻辑都会想哭
    Allianzcortex
        2
    Allianzcortex  
       Sep 2, 2016
    if 'sub_switch' in kwarg:
    kwarg.pop()

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