python中条件运算符的编码风格

时间:2014-07-25 14:02:31

标签: python coding-style switch-statement conditional-statements

我希望得到开发者关于下一代码示例的意见。哪个代码更具可读性?哪种风格更好?

注意:表达式int(a is not None) + 3*int(b is not None) + 5*int(a != b)会返回所列条件的所有组合值的唯一代码。

对不起我的英语。我想让它变得更好。

首先:

if (a is not None) and (b is not None) and (a != b):
   exit()
elif (a is not None) and (b is not None) and (a = b):
   func1()
elif (a is not None) and (b is None):
   func2()
elif (a is None) and (b is not None):
   func3()
elif (a is None) and (b is None):
   func4

第二

code = int(a is not None) + 3*int(b is not None) + 5*int(a != b)
if code == 9:
   exit()
elif code == 4:
   func1()
elif code == 1:
   func2()
elif code == 3:
   func3()
elif code == 0:
   func4()

第三

code = int(a is not None) + 3*int(b is not None) + 5*int(a != b)    
switch = {9:exit, 4:func1, 1:func2, 3:func3, 0:func4}
switch[code]()

1 个答案:

答案 0 :(得分:4)

我愿意:

if a is None:
    if b is None: func4()
    else: func3()
else:
    if b is None: func2()
    elif a == b: func1()
    else: exit()

我绝对不是int转换的粉丝。而且,更理想的情况是,a和b的结构允许您只检查not a而不是a is None,这将更加清晰。

如果您需要将布尔标志编码为数字,我还建议您使用基数2(1,2,4 ......)而不是基数系统。使用(1,3,5 ..) - 如果你受空间限制(保存压缩数据,例如Chess bitboards或许多快速网络IO)可能有意义,但如果你不这样做有一个疯狂的要求,请记住:

  

"过早的优化是万恶之源。"唐纳德克努特