2017-07-02 79 views
-3

嘿所以有一天,我在亂搞一些代碼,它給了我這個錯誤。Python |看到列表是否有元素時出現錯誤

if clearargs[1] == "history": \n IndexError: list index out of range

elif startswith(ui, "clear") or startswith(ui, "clr"): 
    clearargs = ui.split() 
    if len(clearargs) < 1: 
     refs.clearscr("Windows", os) 
    else: 
     if clearargs[1] == "history": 
      history = [] 
      os.remove(hfilepath) 
     elif clearargs[1] == "exthistory": 
      extendedhistory = [] 
      os.remove(ehfilepath) 

BTW大多數功能都是自定義的

+0

(這可能有助於重新訪問關於序列「起源」的[文檔](https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range)。 ) – greybeard

回答

1

的列表索引從零開始。

因此,如果列表的長度恰好等於1,那麼clearargs[0]就是對列表中第一個值的正確訪問。

當詢問是否得到clearargs[1]的價值,你認爲這個列表的長度至少2

0
len(clearargs < 1)所以唯一有效的索引是 clearargs[0]。你正在

else塊將只執行一個邏輯錯誤。

相關問題