2017-07-27 270 views
2

我的代碼工作它創建了一個列表,然後同時採用「或」與「和」的條件做進一步的動作:嵌套「和/或」 if語句

a= ["john", "carlos", "22", "70"] 

if (("qjohn" or "carlos") in a) and (("272" or "70") in a): 
    print "true" 
else: 
    print "not true" 

輸出:

not true 

當我這樣做:

a= ["john", "carlos", "22", "70"] 

if ("qjohn" or "cdarlos" in a) and ("272" or "d70" in a): 
    print "true" 
else: 
    print "not true" 

輸出"true"

我沒有得到的是**carlos and 70**應該等於true,但它打印「不正確」。這個錯誤的原因是什麼?謝謝

+0

並不完全是欺騙,但具有相同的基本問題涉及:如何測試對多值一個變量? ](https://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – glibdud

回答

7

兩種方法都不正確。請記住是一個短路操作,所以它沒有做什麼你認爲它的作用:

它只有第一個是虛假評估的第二個參數。

然而,非空字符串總是True,使得第一情況下,只有用於第一非空字符串的容納檢查而第二從未執行與in容納檢查在所有的,因此,它是總是True

你想要的是:

if ("qjohn" in a or "carlos" in a) and ("272" in a or "70" in a): 
    ... 

如果項目測試是更長的時間,你能避免使用any這就像or也短路,一旦項目測試True的一個重複or

if any(x in a for x in case1) and any(x in a for x in case2): 
    ... 
+0

可能很有用:https:// stackoverflow。com/questions/16679272/logic-statements-not-and-or-in-python – Darkaird

+0

非常感謝您的詳細描述以及它是如何工作的 –

1
b = set(a) 
if {"qjohn", "carlos"} & b and {"272", "70"} & b: 
    .... 

該條件是True如果集合的交集resul ts在非空集合(成員測試)中 - 測試非空集合的真實性在這方面是相當pythonic。


或者,使用set.intersection

if {"qjohn", "carlos"}.insersection(a) and {"272", "70"}.insersection(a): 
    .... 
+0

如果使用'intersection'方法,則不需要預先計算集合'b';該方法可以採用任何可迭代的參數。 '{「qjohn」,「carlos」}。intersection(a)'等等(你是否想這麼做取決於'a'有多大] – chepner

+0

@chepner謝謝。我認爲這是一個被低估的解決方案。 –

0

的兩個不正確。你理解錯誤的邏輯。

("qjohn" or "carlos") in a相當於"qjohn" in a

"qjohn" or "cdarlos" in a相當於"qjohn" or ("cdarlos" in a)