"not in" 成员运算符结合 "or" 布尔运算符 (Python)
"not in" membership operator combined with "or" Boolean operator (Python)
我面临着看似微不足道但非常烦人的难题。在使用 "not in" 运算符结合布尔值 "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 参考资料,但它只会增加混乱。有人可以阐明这一点吗?
请注意,not in
的结合力比 and
和 or
都强。所以 #4 按照你的预期被解析,而 #5 等于 if ("name") or ("income" not in data):
– 因为非空字符串在 python 中是真实的,这意味着它总是在 "not found" 分支中结束.
我面临着看似微不足道但非常烦人的难题。在使用 "not in" 运算符结合布尔值 "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 参考资料,但它只会增加混乱。有人可以阐明这一点吗?
请注意,not in
的结合力比 and
和 or
都强。所以 #4 按照你的预期被解析,而 #5 等于 if ("name") or ("income" not in data):
– 因为非空字符串在 python 中是真实的,这意味着它总是在 "not found" 分支中结束.