我制作了一个小“控制台”,用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
可以动态分配
有什么帮助吗
当你在做:
最后一次迭代尝试在
len(lst)
访问lst
,这是越界的你应该这样做:
如果希望避免附加第一个元素
如果您只是尝试复制新列表中的元素,请执行以下操作:
相关问题 更多 >
编程相关推荐