Pythonic制作xor测试的方法

时间:2014-11-03 12:27:13

标签: python

写入检查两个变量都不能为none的条件的pythonic方法是什么,并且这两个变量也不能不是None。例如

if a is None and b is None: raise SystemExit(1)
if a is not None and b is not None: raise SystemExit(1)
# rest of the code

2 个答案:

答案 0 :(得分:1)

if (a is None) != (b is None):
    raise SystemExit("kkthxbye")
# remainder of code

What's the difference between XOR and NOT-EQUAL-TO?

答案 1 :(得分:-1)

您可以尝试if all((a,b is not None)): pass

In [31]: a = 1

In [32]: b = 1

In [33]: all((a,b is not None))
Out[33]: True

In [34]: b = None

In [35]: all((a,b is not None))
Out[35]: False

注意:ab的值设置为0将产生True

<强> Python化吗

In [36]: len('if a is not None and b is not None')
Out[36]: 34

In [37]: len('all((a,b is not None))')
Out[37]: 22