2016-10-18 60 views
0

我需要檢查列表長度的東西。也許這樣的事情,但是這並不工作:根據可能值列表檢查值

if len(list) != 1 or 2: 
    # Do something 

if len(list) == 1 or 2: 
    # Do something different 

好吧,我想通了這一點自己:

if len(list) == 1: 
    # Do something 
elif len(list) == 2: 
    # Do the same something 

if len(list) != 2: 
    # Do something different 
elif len(list) != 1: 
    # Do something different 
+0

您是否需要將比較作爲範圍或可能的數字列表?如果它等於1,2,5或6,你會做些什麼嗎? – Hoopdady

+0

不,只有一個號碼 – ComputerExpert69

回答

3

喜歡的東西

if 1 <= len(list) <= 2: 
    ... 

或:

if len(list) in (1, 2): 
    ... 

應該工作

+0

我會很快嘗試這個謝謝你的快速回復! – ComputerExpert69

+0

好吧,你的第二個建議似乎返回True或False ... – ComputerExpert69

+0

這兩個都返回true或false – ComputerExpert69