为什么我在这段代码中得到IndexError:list index超出范围?

时间:2015-04-15 03:33:52

标签: python sorting indexing double direction

我试图进行双向冒泡排序。在奇数迭代中,它会向右气泡和排序,在偶数迭代中,它会向左边冒泡并排序。

def main():

    myList = [10,9,8,7,6,5,4,3,2,1]
    lengthOfList = len(myList)
    firstThresh = 0
    lastThresh = lengthOfList
    oddPass = True
    while firstThresh <= lastThresh:
        if oddPass == True:
            for index in myList[firstThresh:lastThresh]:                
                if myList[index] > myList[index+1]:      <==================
                    temp = myList[index]
                    myList[index] = myList[index+1]
                    myList[index+1] = temp
                    print(myList)
                    oddPass = False
            lastThresh -= 1
        else:
            for index in reversed(myList[firstThresh:lastThresh]):
                if myList[index] < myList[index-1]:
                    temp = myList[index]
                    myList[index] = myList[index-1]
                    myList[index+1] = temp
                    print(myList)
                   oddPass = False
            firstThresh += 1
main()

错误: 第22行,在bubbleSort2Way中     如果myList [index]&gt; myList中[指数+ 1]: IndexError:列表索引超出范围

我把箭头放在问题所在的位置。 我是编程的初学者,所以如果它很明显我很抱歉! 任何帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

该行

for index in myList[firstThresh:lastThresh]:

正在使用myList中的值,而不是索引。因此,代码尝试访问仅包含10个元素的列表中的第11个元素(索引&#34; 10&#34;)并且超出范围错误。

要在循环中使用索引,请将此行更改为

for index, value in enumerate(myList[firstThresh:lastThresh]):
相关问题