Python - 检查列表是否包含元素或 n 时出错

2024-06-16 11:22:58 发布

您现在位置: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)

顺便说一句,大多数函数都是自定义的


Tags: of代码uiindexifos错误out
2条回答

else块将仅在len(clearargs < 1)时执行,因此唯一有效的索引是clearargs[0]。这是一个逻辑错误

列表索引从零开始

因此,如果列表的长度正好是一,那么clearargs[0]就是对列表中第一个值的正确访问

当要求从clearargs[1]获取值时,假设列表的长度至少为2

相关问题 更多 >