2013-03-22 64 views

回答

2

我不確定它是否更好/正確,但是您也可以測試某個列表是否具有isinstancetype函數列表。

例如

a = [1,2,3] 
b = (1,2,3) # Not a list 

type(a) == type([]) # True 
type(b) == type([]) # False 

type(a) is list  # True 
type(b) is list  # False 

isinstance(a, list) # True 
isinstance(b, list) # False 

第一種方法可能並不理想,第二個可能會更好,如果你使用type,但我覺得一般的共識是,isinstance一般都比較好。

編輯:Some discussion about the difference between the two approaches

所以,我想你的代碼看起來是這樣的:在Python

if(isinstance(myList[0][0], list)): 
    # Use myList[0][0][0] 
else: 
    # Use myList[0][0] 
+0

處理例外的是,檢查型快得多。除此之外,「最好能夠寬恕而不是要求允許」 – newtover 2013-03-22 08:33:57

+0

@新的,即使這是真的(我從來沒有聽說過,[this](http://stackoverflow.com/questions/5589532/try-catch - 或 - 速度驗證)會另有說明 - 我的猜測是,好處取決於拋出異常的次數),捕獲異常似乎對於像這樣直截了當的事情太過火腿。 – jedwards 2013-03-22 08:41:04

+0

我想我會爲你的方法去做,從我所看到的(在職業世界中)只有在沒有其他方式時纔會提出異常。 – 2013-03-22 08:54:01