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

2019-07-13 20:39:46 +08:00
 ladypxy

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

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 来做啊。 请教大家这段代码有啥优化建议么

5361 次点击
所在节点    Python
21 条回复
imycc
2019-07-14 23:30:09 +08:00
`list_a`跟`i`跟`keyword`应该是你简写给我们看的时候写错了,几个变量有点乱,不好说怎么优化。

单说下面那一部分用`if...elif...elif...elif`会好点,减少缩进的层级。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/582721

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX