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
ladypxy
V2EX  ›  Python

Python 中 if..else 的优化。。。

  •  
  •   ladypxy · 2019-07-13 20:39:46 +08:00 · 5300 次点击
    这是一个创建于 1720 天前的主题,其中的信息可能已经有所发展或是发生改变。

    新手,按照逻辑写了个循环。如下

    list_a= []
    old = []
    new = []
    test = []
    ...
    
    for i in list_a:
        if 'keyword' in list_a[0]:
            if list_a[1] == A:
                new.append[list[2]]
            else:
                old.append[list[2]]
        else:
            if list_a[1]== B and ConditionB:
                test.append[list[2]]
    
    if len(old) == 0 and len(new)>10:
        dosomething()
    else:
        if len(new) < len(old) and len(test) ==0:
            dosomething2(0)
        else:
            if len(test)==0:
                dosomething3()
            else:
                if len(test) > 5:
                    dosomething4()
    

    老码农同事说我 if else 写的太多,让别人不容易看懂,建议优化下代码比如用 If .. continue。 但是我想了下似乎这种有众多子条件的似乎不太适合用 if ...contiune 来做啊。 请教大家这段代码有啥优化建议么

    第 1 条附言  ·  2019-07-13 22:55:18 +08:00
    补充下,因为程序有字数限制,所以像下面这写法,字数就会比我主楼里的多很多。。。容易超标

    if 'keyword' in list_a[0] and list_a[1] == A:
    elif 'keyword' in list_a[0] and list_a[1] != A:
    21 条回复    2019-07-14 23:30:09 +08:00
    Yvette
        1
    Yvette  
       2019-07-13 20:44:56 +08:00   ❤️ 1
    misaka19000
        2
    misaka19000  
       2019-07-13 20:56:18 +08:00 via Android
    下面那个为啥不用 elif
    uyhyygyug1234
        3
    uyhyygyug1234  
       2019-07-13 21:03:39 +08:00
    @Yvette 这个,,,把所有的 css 都拿掉了,有 gnu 的感觉。。。。
    ladypxy
        4
    ladypxy  
    OP
       2019-07-13 21:11:14 +08:00
    @misaka19000 可以用 elseif。。。主要用 else 我个人感觉更好理解啊。。
    secondwtq
        5
    secondwtq  
       2019-07-13 21:13:52 +08:00 via iPad
    确实是有一定优化空间的,我能想到的:

    第一段的 append[list[2]] 这个逻辑是重复的,你可以把 if 判断抽出来成一个变量或者函数,然后再 append

    下面那个可以单独搞一个函数,然后 if len(old) == 0 and len(new)>10: return dosomething() 这样
    cdwyd
        6
    cdwyd  
       2019-07-13 21:17:06 +08:00 via Android
    看着不舒服,我习惯把一种情况这写在一起
    比如
    if 'keyword' in list_a[0] and if list_a[1] == A:
    pass
    lhx2008
        7
    lhx2008  
       2019-07-13 21:17:57 +08:00
    if len(old) == 0 and len(new)>10:
    dosomething()
    return;

    if len(new) < len(old) and len(test) ==0:
    dosomething2(0)
    return;
    if len(test)==0:
    dosomething3()
    return
    if len(test) > 5:
    dosomething4()
    return
    ysoserious
        8
    ysoserious  
       2019-07-13 21:48:07 +08:00 via Android
    这样写,时间久了可能自己都忘了,实在不行就写点注释把逻辑注释出来就好了。同 5 楼,一般遇到这样的情况就把重复部分提取出来做 function 调用。
    starsriver
        9
    starsriver  
       2019-07-13 21:51:50 +08:00 via Android
    同七楼,面向未来写法
    ladypxy
        10
    ladypxy  
    OP
       2019-07-13 22:06:26 +08:00 via iPhone
    @lhx2008 我也考虑过这种写法,但是感觉这样写效率不如我那样写啊。我的写法满足了 if 额度条件,就不会再去 elif 里做判断。而你这个写法,会把所有的 if 做一个判断啊,哪怕是在第一个 if 就满足了。
    wi
        11
    wi  
       2019-07-13 22:10:23 +08:00
    多用 return,少用 else,也许有的根本就不好优化,看你这个方法在干什么咯,看着头就大,怎么有这么多 else
    yumenoks
        12
    yumenoks  
       2019-07-13 22:16:35 +08:00
    if 'keyword' in list_a[0]:
    if list_a[1] == A:
    =============
    这里可不可以这个 if 'keyword' in list_a[0] and list_a[1] == A:
    lhx2008
        13
    lhx2008  
       2019-07-13 22:27:15 +08:00
    @ladypxy #10 最后一节要 return 了再用,前面就 if else
    lhx2008
        14
    lhx2008  
       2019-07-13 22:27:36 +08:00
    @ladypxy #10 如果不是最后一节要用,就拆函数。
    BruceLi
        15
    BruceLi  
       2019-07-13 22:30:47 +08:00
    可以用 filter 和 lambda 表达式
    ladypxy
        16
    ladypxy  
    OP
       2019-07-13 22:53:21 +08:00
    @yumenoks 可以。但是这么写有个问题。

    ```
    if 'keyword' in list_a[0]:
    if list_a[1] == A:
    new.append[list[2]]
    else:
    old.append[list[2]]
    ```
    这段我就要写成
    ```
    if 'keyword' in list_a[0] and list_a[1] == A:
    elif 'keyword' in list_a[0] and list_a[1] != A:

    ```
    这样字数就变多了。。。这程序有大小限制。。。这么写容易超出字数限制。。
    skywatcher
        17
    skywatcher  
       2019-07-14 00:14:08 +08:00
    说实话,真的很难看懂😂你可以把这串代码要做什么详细描述一下,可能大家能提供更有效、简洁的写法
    skywatcher
        18
    skywatcher  
       2019-07-14 00:37:37 +08:00
    ```python
    def process():
    for i in range(len(list_a)):
    if 'keyword' in list_a[i]:
    if list_a[i] == A:
    new_.append(list_[i])
    else:
    old.append(list_[i])
    elif list_a[i]== B and ConditionB:
    test.append(list_[i+1])

    # situation 1: some description
    if len(old) == 0 and len(new_)>10:
    do_something()
    return

    # situation 2: some description
    if len(new_) < len(old) and len(test) ==0:
    do_something2()
    return

    # situation 3: some description
    if len(test) != 0 and len(test) > 5:
    do_something4()
    else:
    do_something3()
    ```
    lynskylate
        19
    lynskylate  
       2019-07-14 00:47:10 +08:00
    因为不知道你具体逻辑 只能简单的帮你优化一下了
    ```python
    list_a = []
    old_list = []
    new_list = []

    for i in list_a:
    k, w, res, *_ = list_a # 使用解包,变量名再优化下可以增加可读性
    if 'keyword' in k and w == A:
    new_list.append(res)
    else:
    old_list.append(res)


    old_list_length = len(old_list)
    new_list_length = len(new_list)

    if old_list_length == 0 and new_list_length > 10:
    do_something()
    return # 如果后面没有的话,直接在此处 return 减少 if else

    if new_list_length < old_list_length and len(test) == 0
    dosomething2(2)
    return # 同上

    if len(test) == 0:
    dosomething3()
    return # 同上

    if len(test) > 5:
    dosomething4()
    ```
    如果知道你具体逻辑,这个判断应该是能优化不少的。
    vkhsyj
        20
    vkhsyj  
       2019-07-14 17:02:54 +08:00
    把这段代码拆分成两个函数看起来就会好很多了
    imycc
        21
    imycc  
       2019-07-14 23:30:09 +08:00
    `list_a`跟`i`跟`keyword`应该是你简写给我们看的时候写错了,几个变量有点乱,不好说怎么优化。

    单说下面那一部分用`if...elif...elif...elif`会好点,减少缩进的层级。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3152 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 12:40 · PVG 20:40 · LAX 05:40 · JFK 08:40
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.