为什么 AND、OR 运算符会为 Boolean 和 sets in python 等数据类型提供单边输出?

Why does the AND, OR operator gives one sided output for data types like Boolean and sets in python ?

# FOR SETS
a=set([1,2,3])
b=set([4,5,6])

print(a and b) #always prints right side value that is b here
print(a or b) #always prints left side value that is a here
print(b and a)#prints a as its on right
print(b or a)#prints b as its on left


#FOR BOOLEANS
print(False and 0) #prints False as it is on the left
print(0 and False) #prints 0 , same operator is used than why diff output
print(False or '') #prints '' as it is on the right
print('' or False) #prints False as now it is on the right

print(1 or True) #prints 1
print(True or 1) #prints True
print(True and 1)#prints 1
print(1 and True)#prints True

AND 始终打印左侧值,OR 始终打印右侧值 False 类型的 布尔值。反向发生在 True 类型的 布尔值上。

应用于任意数量的 集时,OR 给出最左边的值,AND 给出最右边的值。为什么 ?

Python 参考回答了您的问题。 https://docs.python.org/2/reference/expressions.html#boolean-operations

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

容器类型(例如集合和列表)的值如果为空则被视为假,否则为真。

我不认为这是由于左侧或右侧,而是更多的是如何评估和 - 或。

首先在python中0等于False,1等于True,但是True和False是可以重新赋值的,但是默认0==0或者0==False都是没错。

话虽如此,您现在可以查看 and - or 运算符条件的计算方式。

总结: and 运算符总是在寻找 False (0) 值,如果他在第一个评估的参数上找到它然后他停止,但如果他找到 True 或 1 他必须评估第二个条件以查看它是否为 False。因为 False and 其他的总是错误的。这个 table 可能对你有帮助,看看当我有 0 (False) 答案总是 0 (False)

*and* truth table
0 0 = 0                  
0 1 = 0                  
1 0 = 0                  
1 1 = 1   

有点不同,但机制相同: or 将寻找他找到的第一个 True (1)。因此,如果他首先找到 False,他将评估第二个参数,如果他首先找到 True (1),则他停止。 在这里,当您的答案为 1(True) 时,答案始终为 1(True)

*or* truth table
0 0 = 0
0 1 = 1
1 0 = 1
1 1 = 1

你可以看看其他运算符 google operator truth table 你会得到很多其他更详细的例子。

以你为例:

#FOR BOOLEANS
print(False and 0) #prints False because *and* only need one False
print(0 and False) #prints 0 , because 0 = False and *and* only need one False
print(False or '') #prints '' because *or* is looking for a 1(True) but here both are False so he print the last one
print('' or False) #prints False (same reason as the one above) and he print the last one.

print(1 or True) #prints 1 because it's *or* and he found a True(1)
print(True or 1) #prints True same reason as above 1 = True so...
print(True and 1) #prints 1 because *and* is looking for a False and the first condition is True so he need to check the second one
print(1 and True) #prints True same as above 1 = True so and check for second paramater.