2013-01-15 54 views

回答

4

您可以使用len()檢查索引是否存在與否。

由於len(list)回報像last_index+1

In [18]: a = ['a','c','d'] 

In [19]: len(a)-1 > 4 #or len(a)>4 
Out[19]: False 

In [20]: len(a)-1 > 2 
Out[20]: True 
+2

位的解釋將有助於OP :) ..我的意思是列表索引continue..unlike字典 –

6
if len(a) > 4: 
    # list contains fourth element, a[4] 

try: 
    a[4] # do something with a[4] 
except IndexError: 
    print "there is no element a[4]" 
3

您可以隨時檢查:

if index < len(a): 
    # do stuff 
相關問題