Python3.8:使用append()时的索引器错误

2024-10-02 14:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个小“控制台”,用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

我尝试将cmdRaw之后的每个单词添加到名为args的列表中,该列表由addArgsToList()返回。但我得到的是:

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

我不明白为什么我会得到一个IndexError,因为据我所知,newList可以动态分配

有什么帮助吗


Tags: in命令forinputargsrange单词split
2条回答

当你在做:

for i in range(len(lst)):
    newList.append(lst[i+1])

最后一次迭代尝试在len(lst)访问lst,这是越界的

你应该这样做:

如果希望避免附加第一个元素

def addArgsToList(lst=[]):
    newList = []
    for i in range(1,len(lst)):
        newList.append(lst[i])
    return newList

如果您只是尝试复制新列表中的元素,请执行以下操作:

newList = lst[1:].copy()

相关问题 更多 >