在Python中,
if 1 and 2 not in {0, 1}: # return True
print(True)
if 0 and 2 not in {0, 1}: # return False
print(True)
不知道为什么有人能向我解释一下?
我想你的意思是:
if 1 not in {0, 1} and 2 not in {0, 1}:
按照您的方式,它正在解析(如果1(和(如果2不在{0,1}中("如果1〃;总是决心实现。
您可以使用all
:
mySet = {0,1}
if not all(x in mySet for x in (1,2)):
print(True)
if not all(x in mySet for x in (0,2)):
print(True)
输出:
True
True
这是因为if
由多个条件组成。1
等于True
,0
等于False
,它们大多可以互换使用。
因此:
1 and 2 not in {0, 1}
# is actually
(1) and (2 not in {0, 1})
# which equals to
(True) and (2 not in {0, 1})
# and both of them are True
True and True
# -------------------
# but in this case
0 and 2 not in {0, 1}
# is actually
(0) and (2 not in {0, 1})
# which equals to
(False) and (True)
# that is False
如果你想检查多个值是否在一个序列中,你应该这样做:
1 in {0, 1} and 2 in {0, 1}