如何在Python中檢查多個變數是否與某個值相等?
變數是儲存不同值的實體。每次賦值新值時,前一個值都會被新的值替換。在Python中,變數可以是字母、下劃線、數字,但必須以字母開頭等。可以對多個變數與一個值進行比較;可以使用以下幾種方法在Python中進行檢查。
使用邏輯“或”和“與”
在Python中檢查多個變數是否與某個值相等的一種方法是使用邏輯或和與。與運算子將檢查所有變數是否都等於它們各自的值,而或運算子將檢查是否有任何一個變數等於其各自的值。
示例
在這個示例中,我們將使用與運算子來檢查所有定義的變數是否都等於它們各自的值。以下是可以作為參考的程式碼。
a = 300 b = 400 c = 10 if a == b and b == c and c == a: print("All the variables are equal to their respective values") else: print("All the variables are not equal to their respective values")
輸出
以下是使用與運算子檢查所有多個變數是否都等於它們各自的值的輸出。
All the variables are not equal to their respective values
示例
在這個示例中,我們將使用或運算子來檢查至少一個變數是否等於其各自的值。
a = 300 b = 10 c = 10 if a == b or b == c or c == a: print("All the variables are equal to their respective values") else: print("All the variables are not equal to their respective values")
輸出
All the variables are equal to their respective values
使用變數列表
另一種檢查給定變數是否等於其各自值的方法是使用Python的all()函式和any()函式。
all()函式將檢查給定變數的所有值是否相等,而any()函式將檢查至少一個變數是否等於其各自的值。
示例
在這裡,我們將包含值的變數列表傳遞給all()函式,然後它將返回文字,說明所有變數是否都等於它們各自的值。
a = 300 b = 10 c = 10 if all([a == 300,b == 10,c == 10]): print("All the variables are equal to their respective values") else: print("All the variables are not equal to their respective values")
輸出
All the variables are equal to their respective values
示例
讓我們再看一個使用any()函式檢查至少一個變數是否等於其各自值的示例。
a = 300 b = 10 c = 10 if any([a == 0,b == 0,c == 0]): print("At least one variable is equal to their respective values") else: print("All the variables are not equal to their respective values")
輸出
All the variables are not equal to their respective values
使用字典
我們將使用字典將變數作為鍵,它們各自的值作為值進行儲存。在這裡,為了檢查字典中所有變數或至少一個變數是否等於各自的值,我們將列表推導與locals()函式一起使用。locals()函式用於過濾字典中的變數。
示例
在這個示例中,我們將使用列表推導和locals()函式來檢查字典中的所有變數是否都等於它們各自的值。
a = 300 b = 20 c = 30 d = 340 dic = {"a" : 10,"b" : 20,"c" : 40,"d" : 230} if all([dic[key] == value for key, value in locals().items() if key in dic]): print("All the variables are equal to their respective values") else: print("All the variables are not equal to their respective values")
輸出
All the variables are not equal to their respective values
廣告