首页 > 对于条件分支很多的情况,有没有更Pythonic的写法

对于条件分支很多的情况,有没有更Pythonic的写法

比如五个条件A/B/C/D/E,会有32种情况

if A and B and C and D and E:
    do_one()
elif A and B and C and D and not E:
    do_two()
elif A and B and C and not D and E:
    do_three()
...
...
...
else:
    do_32()

有更简洁的写法吗?


推荐按位进行计算


感觉可以考虑用一下装饰器。

通用的逻辑做wrapper, 然后对于特殊情况hardcode。


You could use a dictionary:

def f(x):
    return {
        'a': 1,
        'b': 2,
    }[x]

来自:http://stackoverflow.com/a/60211
如果需要调用函数,你可以这样

def fun1():
    print("function 1")

def fun2():
    print("function 2")
    
def fun3():
    print("function 3")
    
    
def f(x):
    return {
        'a': fun1,
        'b': fun2,
        'c': fun3
    }[x]
    
rtnFun = f('a')
rtnFun()
rtnFun = f('b')
rtnFun()

很显然,输出为

function 1
function 2

建议每个条件作为一个二进制位或者10进制为,只需要无嵌套的有限个if,然后根据你的取值到一个dict中取得该值对应的函数, 也就是自己根据状态码做一层路由。

【热门文章】
【热门文章】