我创建了一个小的“控制台”,将命令与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是可以动态分配的。
有什么帮助吗?
发布于 2020-02-19 17:09:18
你应该这样做:
如果希望避免追加第一个元素
def addArgsToList(lst=[]):
newList = []
for i in range(1,len(lst)):
newList.append(lst[i])
return newList如果您只是尝试复制新列表中的元素,只需执行以下操作:
newList = lst[1:].copy()发布于 2020-02-19 17:05:16
当你这样做的时候:
for i in range(len(lst)):
newList.append(lst[i+1])最后一次迭代尝试访问超出范围的len(lst)上的lst。
https://stackoverflow.com/questions/60296441
复制相似问题