Python,列表错误:索引器错误:列表索引超出范围

2024-09-27 00:14:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在研究一个程序,它接受一个字符串并按字母顺序(气泡排序)。我做了一段简单的代码来开始我的工作,但是在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编写)


Tags: 答案代码true错误字母fileinsertsorted
1条回答
网友
1楼 · 发布于 2024-09-27 00:14:27

CompOne0开始

CompTwo1开始

add 1一直到CompOne寻址字符串的最后一个字符(这很好)CompTwo试图访问字符串最后一个字符之后的字符。在

我不确定我是否正确地理解了你要做的事,最让我困惑的是:

  • 您是否在every while循环循环循环时将sortingList重新实例化为空列表?在
  • 在每个while循环中,您将charn和“n+1”放入数组中的某些索引处
  • 您的sortingList被排序两次(sorted(…)),这将创建两次新列表,这是非常不必要的-您可以简单地对它排序一次并将其存储在您访问的temp变量中。为什么在这里使用.insert作为索引,由于前面的sortedList=[]两行字符,列表中的两个字符旁边是空的

您需要注意输入数组的长度,CompTwo不能超过这个长度。在

相关问题 更多 >

    热门问题