在python中,为什么AND、OR运算符会为Boolean和set之类的数据类型提供单边输出?

2024-04-26 04:30:11 发布

您现在位置: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

对于False类型的boolean,始终打印左侧值和/或始终打印右侧值。如果True类型为boolean,则相反。你知道吗

当应用于任何数量的集时,或给出最左边的值和最右边的值。为什么?你知道吗


Tags: orandtherightfalsetrueforis
2条回答

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.

容器类型的值(如集合和列表)如果为空则视为false,否则视为true。你知道吗

我不认为这是由于左侧或右侧,但更多的是如何和-或评估。你知道吗

首先,在python中,0等于False,1等于True,但是可以重新分配True和False,但是默认情况下,0==0或0==False都是True。你知道吗

这就是说,您现在可以查看and-or运算符条件是如何计算的。你知道吗

总结: 操作符总是在寻找一个假(0)值,如果他在第一个求值的参数上找到它,那么他就停止,但是如果他找到真或1,他就必须求值第二个条件,看看它是不是假。因为虚假的东西总是虚假的。这个表可能会帮你,看我什么时候有0(假)答案总是0(假)

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

有点不同,但机制相同: 会寻找他找到的第一个真的。因此,如果他首先发现False,他将计算第二个参数,如果他在第一个参数中发现True(1),那么他停止。 这里当你有一个1(真)答案总是1(真)

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

你可以看看其他运营商只是谷歌运营商真值表,你会有很多其他更详细的例子。你知道吗

例如:

#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.

相关问题 更多 >