两者都不是

时间:2019-04-12 14:04:29

标签: python python-3.x

我需要一个类的两个属性都为None或都为int。已经进行了检查,以确保如果将它们都设置为None,则它们将是整数。因此,在__init__方法的末尾,我正在调用一个小函数,该函数检查两种顺序的类型是否不同:

def both_none_or_both_something_else(a,b): 
    if a is None and b is not None:
        return False
    if b is None and a is not None:
        return False
    return True

>> both_none_or_both_something_else(5,None)  # False

>> both_none_or_both_something_else(None,3)  # False

>> both_none_or_both_something_else(5,20)  # True

>> both_none_or_both_something_else(None, None)  # True

是否可以将这两个变量的检查压缩为一行?

5 个答案:

答案 0 :(得分:3)

只需比较None的测试结果:

return (a is None) == (b is None)

答案 1 :(得分:1)

这可能不是您想要的-但比任何一种衬纸都清晰得多。

def both_none(a,b):
   return a is None and b is None

def both_not_none(a,b):
   return a is not None and b is not None

def both_none_or_both_something_else(a,b): 
   return both_none(a,b) or both_not_none(a,b)

答案 2 :(得分:1)

您需要逻辑XOR运算符:如果不同->否,如果相等->真

  

Exclusive或(XOR,EOR或EXOR)是一个逻辑运算符,当两个操作数中的一个为true(一个为true,另一个为false)但都不为true且都不为false时,结果为true。在逻辑条件制作中,当两个操作数均为true时,简单的“或”有点含糊。

def both_none_or_both_something_else(a,b):
    return not bool(a) != bool(b)

print (both_none_or_both_something_else(5,None))
print (both_none_or_both_something_else(None,3))
print (both_none_or_both_something_else(5,20))
print (both_none_or_both_something_else(None,None))

输出:

False
False
True
True

备注:

全部为None或全部为int:

def both_none_or_both_something_else(a,b):
    return not type(a) != type(b)

print (both_none_or_both_something_else(5,None))
print (both_none_or_both_something_else(None,3))
print (both_none_or_both_something_else(5,20))
print (both_none_or_both_something_else(None,None))

输出:

False
False
True
True

答案 3 :(得分:1)

你可以说些类似的东西

all(x is None for x in (a, b)) or all(x is not None for x in (a,b))

但是我不能真的说这是一种进步。如果您反复需要这样做,则可以通过将它们封装到谓词中来达到一定的优雅程度:

def all_none(*args):
    return all(x is None for x in args)

def none_none(*args):
    return all(x is not None for x in args)

答案 4 :(得分:-1)

只需:

return type(a) == type(b) and type(a) in [int, type(None)]