sset方法來檢查數組元素是否存在,在Python中無對應函數,在Python中一般可以通過異常來處理數組元素不存在的情況,而無須事先檢查
Python的編程理念是“包容錯誤”而不是“嚴格檢查”。舉例如下:
代碼如下:
Look before you leap (LBYL):
if idx < len(array):
array[idx]
else:
#handle this
Easier to ask forgiveness than permission (EAFP):
try:
array[idx]
except IndexError:
#handle this
Look before you leap (LBYL):
if idx < len(array):
array[idx]
else:
#handle this
Easier to ask forgiveness than permission (EAFP):
try:
array[idx]
except IndexError:
#handle this
所以在Python中一般可以通過異常來處理數組元素不存在的情況,而無須事先檢查。
如果不希望看見異常處理,也可以像下面這樣:
代碼如下:
if 'test' in ['demo','example']:
...
else:
...