[英]Why am I getting IndexError: list index out of range in this code?
Im trying to make a two way bubble sort. 我正在尝试进行双向气泡排序。 on odd iterations, it bubbles and sorts to the right, on even iterations, it bubbles and sorts to the left. 在奇数次迭代中,它冒泡并在右侧排序,在奇数次迭代中,它冒泡并在左侧排序。
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()
The error: line 22, in bubbleSort2Way if myList[index] > myList[index+1]: IndexError: list index out of range 错误:如果myList [index]> myList [index + 1],则在bubbleSort2Way中的第22行:IndexError:列表索引超出范围
I put the arrow where the problem is. 我把箭头放在问题所在的位置。 I am a beginner at programming so if its obvious im sorry! 我是编程的初学者,所以很抱歉! Any help would be great! 任何帮助将是巨大的!
The line 线
for index in myList[firstThresh:lastThresh]:
is using the values from myList
, not the index. 正在使用myList
的值,而不是索引的值。 So the code is trying to access the 11th element (index "10") on a list with only 10 elements and getting an out of range error. 因此,代码尝试访问仅包含10个元素的列表中的第11个元素(索引“ 10”),并出现超出范围的错误。
To use the index in your loop, change this line to 要在循环中使用索引,请将此行更改为
for index, value in enumerate(myList[firstThresh:lastThresh]):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.