“不在”成员身份运算符与“或”布尔运算符组合(Python)

2024-04-26 22:57:03 发布

您现在位置: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参考资料,但这只会增加混乱。有人能解释一下吗?你知道吗


Tags: orandnameindataif字典not
1条回答
网友
1楼 · 发布于 2024-04-26 22:57:03

注意,not inandor结合更强烈。所以#4会像您所期望的那样被解析,而#5等于if ("name") or ("income" not in data):——因为在python中非空字符串是真实的,这意味着它总是以“找不到”分支结束。你知道吗

相关问题 更多 >