多条件条件有效

时间:2016-11-03 03:17:59

标签: python loops combinatorics

如何在python中以更有效的方式执行以下代码?输入标志是二进制值。输出取决于标志的所有可能排列。

def f1():

    return 1

def f2():

    return 2

def f3():

    return 3    


def g(p1, p2, p3):

    if p1 ==  1 & p2 == 0 & p3 == 0:
        f1()

    elif: p1 == 0 & p2 == 1 & p3 == 0:
        f2()

    elif: p1 == 0 & p2 == 0 & p3 == 1:
        f3()

    elif: p1 == 1 & p2 == 1 & p3 == 1:
        f1()
        f2()

等等。

2 个答案:

答案 0 :(得分:3)

您可以将这三个位组合成一个数字,然后像这样测试该数字的值:

def g(p1, p2, p3):

   v = (p1 << 2) + (p2 << 1) + p3

    if v == 4: # 100
        f1()
    elif v == 2: # 010
        f2()
    elif v == 1: # 001
        f3()
    elif v == 7: # 111
        f1()
        f2()

答案 1 :(得分:1)

如果要将参数(p1, p2, p3)用作标记,则始终可以使用*args将这些参数打包为列表(请参阅thisthis和{{3并将你的函数放在一个列表中(是的,Python允许你这样做)并得到类似的东西:

def f1():
    return 1

def f2():
    return 2

def f3():
    return 3 

def g(*ps):
    functions = [f1, f2, f3]
    for i, p in enumerate(ps):
        if p == 1:  # Could do just `if p:` (0 evaluates to False, anything else to True)
            print(functions[i])()  # Notice the () to actually call the function 

if __name__ == "__main__":
    print("Run 1 0 0")
    g(1, 0, 0)
    print("Run 1 1 0")
    g(1, 1, 0)
    print("Run 0 1 0")
    g(0, 1, 0)
    print("Run 1 1 1")
    g(1, 1, 1)

根据this ShadowRanger的答案,你甚至可以将代码缩短一点。例如,使用comment

def g(*ps):
    functions = [f1, f2, f3]
    for function, p in zip(functions, ps):
        if p:
            print(function())

或使用zip(您需要在文件顶部import itertools):

def g(*ps):
    functions = [f1, f2, f3]
    for function in itertools.compress(functions, ps):
        print(function())