“不在”成员运算符与“或”布尔运算符(Python)结合使用

时间:2015-09-01 06:56:16

标签: python membership

我面对的似乎是微不足道的,但却是非常讨厌的难题。在使用“not in”运算符检查成员资格时,结合以下字典中的Boolean“and”和“or”:

    data = {"name": "david", "age": 27, "income": "absurd"}

我发现:

#1 - found
if "name" not in data:
    print "not found"
else:
    print "found"

#2 - found
if "name" not in data and "income" not in data:
    print "not found"
else:
    print "found"

#3 - found
if "name" and "income" not in data:
    print "not found"
else:
    print "found"

#4 - found
if "name" not in data or "income" not in data:
    print "not found"
else:
    print "found"

#5 - NOT found (though it should be?)
if "name" or "income" not in data:
    print "not found"
else:
    print "found"

对于我的钱#4和#5在逻辑上是相同的,但显然它们不可能。我查看了官方的Python参考资料,但它只是增加了混乱。有人会对此有所了解吗?

1 个答案:

答案 0 :(得分:0)

请注意,import numpy as np import matplotlib.pyplot as plt # Example labelled arrays a and b input_a = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0], [0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0], [0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0], [0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0], [0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 0], [0, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 0], [0, 0, 3, 3, 3, 3, 2, 2, 2, 2, 0, 0], [0, 0, 3, 3, 3, 3, 2, 2, 2, 2, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) input_b = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 3, 3, 3, 3, 3, 0, 0], [0, 0, 1, 1, 1, 3, 3, 3, 3, 3, 0, 0], [0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 0, 0], [0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 0, 0], [0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 0, 0], [0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) # Plot inputs plt.imshow(input_a, cmap="spectral", interpolation='nearest') plt.imshow(input_b, cmap="spectral", interpolation='nearest') # Desired output, union of a and b output = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 0, 0], [0, 0, 1, 1, 1, 2, 3, 3, 3, 3, 0, 0], [0, 0, 1, 1, 1, 4, 7, 7, 7, 7, 0, 0], [0, 0, 5, 5, 5, 6, 7, 7, 7, 7, 0, 0], [0, 0, 5, 5, 5, 6, 7, 7, 7, 7, 0, 0], [0, 0, 5, 5, 5, 6, 7, 7, 7, 7, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) # Plot desired output plt.imshow(output, cmap="spectral", interpolation='nearest') not inand的绑定更强。因此#4会按照您的预期进行解析,而#5等于or - 因为非空字符串在python中是真的,这意味着它总是在“未找到”分支中结束。