簡體   English   中英

為什么AND,OR運算符為Boolean和python中的set之類的數據類型提供單邊輸出?

[英]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

對於布爾類型的False, AND總是打印左側的值,而OR總是打印右側值。 反向會發生True類型的布爾值。

當應用於任意數量的集合時,OR給出最左值,AND給出最右值。 為什么呢

Python參考資料回答了您的問題。 https://docs.python.org/2/reference/expressions.html#boolean-operations

表達式x and y首先計算x ; 如果x為假,則返回其值; 否則,將評估y並返回結果值。

表達式x or y首先計算x ; 如果x為true,則返回其值; 否則,將評估y並返回結果值。

如果容器類型的值(例如集合和列表)為空,則將其視為false;否則將其視為true。

我不認為這是由於左側或右側,而是更多關於如何和-或被評估。

首先,在python中,0等於False,1等於True,但是可以重新分配True和False,但是默認情況下0 == 0或0 == False都為True。

也就是說,您現在可以查看如何和-或操作員條件評估。

總結一下: and運算符始終在尋找False(0)值,如果他在第一個求值參數上找到它,那么他會停止,但是如果他找到True或1,則必須對第二個條件求值以查看它是否為False。 。 因為錯誤其他東西永遠都是錯誤的。 該表可能會對您有幫助,請看我何時有0(假)答案始終為0(假)

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

有點不同,但機制相同: 將尋找他找到的第一個True(1)。 因此,如果他首先發現False,則將評估第二個參數,如果他首先發現True(1),則將停止。 在這里,當您的答案為1(真)時,答案總是1(真)

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

您可以查看其他運算符,只是google運算符真值表,您將擁有很多其他更詳細的示例。

以您為例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM