【发布时间】:2018-05-03 02:21:47
【问题描述】:
我一直在开发一个程序,该程序接受一个字符串并将其按字母顺序排序(冒泡排序)。我编写了一段简单的代码来启动我,但在 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 循环,当我通过这个问题时我会继续这样做) 我想要的输出:
['a', 'b', 'd', 'c']
__________________________
['a', 'b', 'd', 'c']
__________________________
['a', 'b', 'c', 'd']
__________________________
ETC(Will repeat because i haven't closed the while loop)
我得到错误的输出:
['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] 很好,但 aList[compTwo] = sorted(sortingList)[compTwo] 不是(建议它们是相似的代码)
我已经调查了这个问题 1 个半小时,但我还没有找到解决方案,如果你能告诉我问题并深入解释为什么会发生这种情况,我将不胜感激。(我不只是想要答案,但我想解释我做错了什么)同时我正在等待答案和解释,我会自己调查问题。谢谢。 (用python 3.6.1编写)
【问题讨论】:
标签: python list loops python-3.6 bubble-sort