多个条件有效
multiple conditionals effciently
如何在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()
等等。
您可以将这三位组合成一个数字,然后像这样测试该数字的值:
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()
如果你想使用参数 (p1, p2, p3)
作为标志,你总是可以使用 *args
将这些参数打包为一个列表(参见 this, this and this)并将你的函数放在一个列表中(是的,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)
根据ShadowRanger's to this answer, you could even shorten the code a bit more. For instance, using zip
:
def g(*ps):
functions = [f1, f2, f3]
for function, p in zip(functions, ps):
if p:
print(function())
或使用 itertools.compress
(您需要在文件顶部 import itertools
):
def g(*ps):
functions = [f1, f2, f3]
for function in itertools.compress(functions, ps):
print(function())
如何在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()
等等。
您可以将这三位组合成一个数字,然后像这样测试该数字的值:
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()
如果你想使用参数 (p1, p2, p3)
作为标志,你总是可以使用 *args
将这些参数打包为一个列表(参见 this, this and this)并将你的函数放在一个列表中(是的,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)
根据ShadowRanger's zip
:
def g(*ps):
functions = [f1, f2, f3]
for function, p in zip(functions, ps):
if p:
print(function())
或使用 itertools.compress
(您需要在文件顶部 import itertools
):
def g(*ps):
functions = [f1, f2, f3]
for function in itertools.compress(functions, ps):
print(function())