【问题标题】:Python, Lists error: IndexError: list index out of rangePython,列表错误:IndexError:列表索引超出范围
【发布时间】: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


    【解决方案1】:

    CompOne 开始于 0

    CompTwo 开始于 1

    add 1 一直都在 - 直到 CompOne 处理字符串的最后一个字符(这很好)并且CompTwo 尝试访问字符 after 的最后一个字符字符串 -> Indexerror.

    我不确定我是否正确掌握了您尝试做的事情,最让我感到困惑的是:

    • 您在每个 while-loop-round 中将您的 sortingList 重新实例化为一个空列表?
    • 在每个 while 循环中,您将 char n 和 'n+1' 放入数组的某些索引处
    • 您的排序列表被排序了两次(排序(.....)),这会创建两次新列表,这是非常不必要的 - 您可以简单地将其排序一次并将其存储在您访问的临时变量中。为什么在这里使用带有索引的.insert,由于之前的sortedList=[] 几行,列表在您放入的两个字符旁边是空的

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

    【讨论】:

    • 谢谢,您回答了我遇到的问题。我想知道您所说的我对变量进行了两次排序是什么意思,我仔细查看了代码,但看不到任何对它进行了两次排序的东西。唯一一次排序是在:aList[compOne] = sorted(sortingList)[compOne] aList[compTwo] = sorted(sortingList)[compTwo],它们被单独排序。
    • 否 - sorted(sortingList) 将对整个列表进行排序并在新列表上创建一个新副本(它不会就地排序)并且添加的 [compOne] 使用此列表的第 n 个元素- 然后你再次做同样的事情并访问第 n+1 个元素另一个复制和排序的列表。见docs.python.org/3.6/library/functions.html#sorted:o)
    猜你喜欢
    • 2018-04-22
    • 2020-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2017-04-05
    • 2012-07-15
    相关资源
    最近更新 更多