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

时间:2017-11-19 21:42:23

标签: python list loops python-3.6 bubble-sort

我一直在研究一个带字符串并按字母顺序排序的程序(冒泡排序)。我做了一段简单的代码来启动我,但是我在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编写)

1 个答案:

答案 0 :(得分:0)

import imaplib username = "mail@gmail.com" pwd = "pwd" imap_server = "imap.gmail.com" imap_port = 993 conn = imaplib.IMAP4_SSL(imap_server, imap_port) conn.login(username, pwd) CompOne

开始

0CompTwo

开始

1始终为add 1 - 直到CompOne对应字符串的最后一个字符(这很好)并且CompTwo尝试访问之后的字符字符串的最后一个字符 - &gt; Indexerror

我不确定我是否正确掌握了你想做的事情,最让我难以理解的是:

  • 您是否在每个循环回合中将sortingList重新解释为空列表?
  • 在每个while循环中,您将char n和'n + 1'放入数组中的某些索引
  • 你的sortedList被排序两次(排序(.....)),它创建了两次非常不合适的新列表 - 你可以简单地对它进行排序并将其存储在你访问的临时变量中。为什么在这里使用带有索引的.insert,由于sortedList=[]之前的CompTwo对行,因此在您放入的两个字符旁边的列表是空的

您需要注意输入数组的长度,{{1}}不能超过该值。