我有一个函数需要根据输入的查询实例执行查询.. 但是随着条件的增加,我要列出所有这些变得很乏味。 例如: 假设我最初有两个条件:
if (cond_1 == True and cond_2 == False):
do something
elif cond_1 == True and cond_2 == True:
do something else
elif cond_1 == False and cond_2 == True:
do this
....
所以我想如果条件采用二进制值,那么我必须写 2^n 条语句 :(
所以现在我有 3 个条件变量(8 个语句).. 我担心这个数字将来可能会增加。 是否有更好的方法来检查这些条件??
最佳答案
您是否需要始终写出所有 2^n 种可能性?
您必须做的所有事情都不同吗(还有 2^n 个操作?)
不过我可以给一些提示:
不要使用“== True”或“== False”
你写的等于:
if cond_1 and not cond_2:
do something
elif cond_1 and cond_2:
do something else
elif not cond_1 and cond_2:
do this
同时考虑写作:
if cond_1:
if cond_2:
Do something
else:
Do something
else:
if cond_2:
Do something
else:
Do something
您还可以根据值定义函数:
def __init__(self):
self.actions = {
(False, False): action_1,
(False, True ): action_2,
...
}
def action_1(self):
some action
def action_2(self):
some action
....
并调用它:
self.actions[(cond_1, cond_2)]()
如果你想优化选项的数量,以防你有不同的条件和类似的 Action ,看看卡诺 map (它比看起来更容易):
关于python - 如何为所有 2^N bool 条件编写 If 语句(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9525575/