Python I';我正在尝试实现一个函数,将()插入数组
您需要扩展列表,否则将分配给不存在的索引。Python I';我正在尝试实现一个函数,将()插入数组,python,list,Python,List,您需要扩展列表,否则将分配给不存在的索引。 还有,循环 def insertElement(element, position, array): last = len(array) - 1 if position > len(array) or position < 0: print("position does not exist") else: for q in range(len(array)+1, position, -
还有,循环
def insertElement(element, position, array):
last = len(array) - 1
if position > len(array) or position < 0:
print("position does not exist")
else:
for q in range(len(array)+1, position, -1):
array[q+1] = array[q]
print(array)
last += 1
array[position] = element
应从透镜(阵列)-2开始,直到位置-1
因此,您的代码变为:
for q in range(len(array)+1, position, -1):
def插入元素(元素、位置、数组):
last=len(数组)-1
如果位置>透镜(阵列)或位置<0:
打印(“位置不存在”)
其他:
数组。追加(“”)
对于范围内的q(透镜(阵列)-2,位置-1,-1):
数组[q+1]=数组[q]
数组[位置]=元素
正如其他人所指出的,您不能通过分配给不存在的列表位置来实现这一点。必须使用使列表变大的操作:append
或extend
以某种形式,包括+
运算符。这是最容易用切片完成的,例如
def insertElement(element, position, array):
last = len(array) - 1
if position > len(array) or position < 0:
print("position does not exist")
else:
array.append('_')
for q in range(len(array)-2, position-1, -1):
array[q+1] = array[q]
array[position] = element
根据经验法则,更改数组时不要迭代数组。不能通过指定索引来创建新的列表元素q+1
不在列表中,因此您不能分配给array[q+1]
。而且,array[q]
在第一次迭代中不存在,因为您从len(array)+1
开始q
,最后一个索引是len(array)-1
。+1
是打字错误吗?最后一个变量的用途是什么?您从未使用过它。请共享整个错误消息。没有意识到这来自原始代码,我移动了我的注释。
array = array[:position] + [element] + array[position:]