我面对的可能是一个看似微不足道,但却非常恼人的难题。在下列字典上使用“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中非空字符串是真实的,这意味着它总是以“找不到”分支结束。你知道吗相关问题 更多 >
编程相关推荐