[英]Why do I get a “IndexError: list index out of range” error?
I am trying to create a bubble sort in python, but I keep getting the error code: "IndexError: list index out of range". 我正在尝试在python中创建冒泡排序,但我一直收到错误代码:“ IndexError:列表索引超出范围”。 I am not sure where I am going wrong, as I don't know where my code exceeds its bounds:
我不确定我哪里出错了,因为我不知道我的代码超出了范围:
def swaps():
while dataset[i] > dataset[i+1]:
temp = dataset[i]
dataset[i] = dataset[i+1]
dataset[i+1] = temp
print (dataset)
dataset = ["6", "3", "5", "2", "4", "1"]
newset = ["0", "0", "0", "0", "0", "0"]
for i in range(0,6):
newset[i] = swaps()
Any help or advice would be greatly appreciated! 任何帮助或建议,将不胜感激! x
X
range(0, 6)
= [0, 1, 2, 3, 4, 5]
. range(0, 6)
= [0, 1, 2, 3, 4, 5]
When it gets to 5
. 到
5
。 then 5 + 1 = 6
. 那么
5 + 1 = 6
。 and you don't have an item at dataset[6]
. 并且您在
dataset[6]
没有项目。
And as Zach King has pointed out - it's not good practice to use global variables in this case, passing objects through as arguments to a function would be a lot nicer. 正如Zach King指出的那样-在这种情况下使用全局变量并不是一种好习惯,将对象作为参数传递给函数会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.