我一直在研究一个程序,它接受一个字符串并按字母顺序(气泡排序)。我做了一段简单的代码来开始我的工作,但是在shell中运行后不久我遇到了一个问题。 我的代码:
aList = ["b", "a", "d", "c"]
compOne = 0
compTwo = 1
sorting = True
while sorting == True:
print (aList)
sortingList = []
sortingList.insert(compOne, aList[compOne])
sortingList.insert(compTwo, aList[compTwo])
aList[compOne] = sorted(sortingList)[compOne]
aList[compTwo] = sorted(sortingList)[compTwo]
print (aList)
print("__________________________")
compOne = compOne + 1
compTwo = compTwo + 1
我的想法是,它将继续在列表中交换项目,直到它按字母顺序排列(我还没有关闭while循环,当我通过这个问题时,我会继续这样做) 我想要的输出:
^{pr2}$我得到的输出与错误:
['a', 'b', 'd', 'c']
__________________________
Traceback (most recent call last):
File "C:/Users/MyName/Desktop/Python Programs/Projects/Bubble Sort/Test File 4.py", line 10, in <module>
aList[compTwo] = sorted(sortingList)[compTwo]
IndexError: list index out of range
正如您所知,它遇到了要比较的第二组项时遇到了这个错误。因为某种原因
aList[compOne] = sorted(sortingList)[compOne]
很好,但是{
我已经调查这个问题一个半小时了,但没有找到解决办法,如果你能告诉我问题,并深入解释为什么会这样,我将不胜感激。(我不只是想得到答案,我还需要一个关于我做错了什么的解释)与此同时,我正在等待答案和解释,我将亲自调查问题。谢谢。(用python3.6.1编写)
CompOne
从0
开始CompTwo
从1
开始您
add 1
一直到CompOne
寻址字符串的最后一个字符(这很好)CompTwo
试图访问字符串最后一个字符之后的字符。在我不确定我是否正确地理解了你要做的事,最让我困惑的是:
sortingList
重新实例化为空列表?在n
和“n+1”放入数组中的某些索引处.insert
作为索引,由于前面的sortedList=[]
两行字符,列表中的两个字符旁边是空的您需要注意输入数组的长度,
CompTwo
不能超过这个长度。在相关问题 更多 >
编程相关推荐