为什么我得到一个" IndexError:列表索引超出范围"错误?

时间:2017-10-07 14:42:17

标签: python python-3.x

我正在尝试在python中创建冒泡排序,但我不断收到错误代码:" IndexError:列表索引超出范围"。我不知道我哪里出错了,因为我不知道我的代码超出了界限:

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()

非常感谢任何帮助或建议! X

1 个答案:

答案 0 :(得分:0)

range(0, 6) = [0, 1, 2, 3, 4, 5]。当它到达5时。然后5 + 1 = 6。并且您在dataset[6]没有项目。

正如Zach King所指出的那样 - 在这种情况下使用全局变量并不是一个好习惯,将对象作为参数传递给函数会更好。