Python 3.8:使用 append() 时的 IndexError

我做了一个小的“控制台”,将命令拆分为.我将“命令”(第一个“单词”与)与第一个单词后面的“参数”分开。下面是生成错误的代码:split()input()


cmdCompl = input(prompt).strip().split()

cmdRaw = cmdCompl[0]

args = addArgsToList(cmdCompl)

addArgsToList()功能:


def addArgsToList(lst=[]):

    newList = []

    for i in range(len(lst)):

        newList.append(lst[i+1])

    return newList

我尝试将后面的每个单词添加到由 返回的列表中。但我得到的是:cmdRawargsaddArgsToList()


Welcome to the test console!


Type help or ? for a list of commands


testconsole >>> help

Traceback (most recent call last):

  File "testconsole.py", line 25, in <module>

    args = addArgsToList(cmdCompl)

  File "testconsole.py", line 15, in addArgsToList

    newList.append(lst[i+1])

IndexError: list index out of range

我不知道为什么我会得到一个,因为据我所知,可以动态分配。IndexErrornewList


有什么帮助吗?


长风秋雁
浏览 156回答 2
2回答

慕妹3146593

你应该这样做:如果您希望避免追加第一个元素def addArgsToList(lst=[]):&nbsp; &nbsp; newList = []&nbsp; &nbsp; for i in range(1,len(lst)):&nbsp; &nbsp; &nbsp; &nbsp; newList.append(lst[i])&nbsp; &nbsp; return newList如果您只是尝试复制新列表中的元素,只需执行以下操作:newList = lst[1:].copy()

慕勒3428872

当您执行以下操作时:for&nbsp;i&nbsp;in&nbsp;range(len(lst)): &nbsp;&nbsp;&nbsp;&nbsp;newList.append(lst[i+1])最后一次迭代尝试访问哪个是越界的。lstlen(lst)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python