2016-04-13 22 views
0

有沒有辦法縮短這個if語句?python if語句不等於某些數字

if i != 9 or i != 23 or i != 25 or i != 33 or i !=35: 
    print(i) 
+0

這對於一些元素並不重要,你可以使用元組,列表等。但是如果你有很多值來檢查一組將會快很多 –

+1

謝謝,發佈答案,我會接受。 :) – Coolcrab

回答

3

您可以使用set,並檢查是否不在集合

invalid_set = {9, 23,25, 33, 35} 
if i not in invalid_set: 
    # all good 

一組查找如果O(1) VS O(n)與列表,元組等。

0

怎麼樣

if i not in [9,23,25,33,25]: 
    print(i)