2017-07-02 82 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块将只执行一个逻辑错误。

相关问题