V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2016-09-02 16:56:52 +08:00 · 2017 次点击
    这是一个创建于 2764 天前的主题,其中的信息可能已经有所发展或是发生改变。

    以下代码 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 条回复    2016-09-10 12:45:25 +08:00
    BOYPT
        1
    BOYPT  
       2016-09-02 17:04:57 +08:00
    写到这样的逻辑都会想哭
    Allianzcortex
        2
    Allianzcortex  
       2016-09-02 17:14:37 +08:00
    if 'sub_switch' in kwarg:
    kwarg.pop()

    这样子的。。。??
    264768502
        3
    264768502  
    OP
       2016-09-02 20:02:48 +08:00 via Android
    或许这样更好
    ```python
    try:
    if kwarg.pop('sub_switch'):
    do()
    except KeyError:
    if main_switch:
    do()
    ```
    just4test
        4
    just4test  
       2016-09-05 09:19:15 +08:00
    首先你不能
    temp = kwarg.get('sub_switch')
    么?
    264768502
        5
    264768502  
    OP
       2016-09-05 15:29:08 +08:00
    @just4test 可以赋值先,不过逻辑判断的过程依然很丑陋
    264768502
        6
    264768502  
    OP
       2016-09-10 12:45:25 +08:00 via Android
    果然抛开业务谈逻辑不是很好,这里还有个性能问题
    查了一下,当 key 高概率在字典,可以用 try.否则先查看有没有,再执行逻辑,性能上会更好
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5390 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 06:52 · PVG 14:52 · LAX 23:52 · JFK 02:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.