【问题标题】:Why am I getting the error message: list index out of range in Python为什么我收到错误消息:Python 中的列表索引超出范围
【发布时间】:2014-02-16 14:52:25
【问题描述】:

当我尝试使用任何类型的列表运行此程序时,我得到一个 indexerror: 列表索引超出范围。
有什么想法吗?

def binaryListSort(aList):
    '''takes a list of binary numbers and puts them in ascending order
    inputs: a list of binary integers, aList Outputs: a new list with numbers
    in ascending order.'''

    if aList[0] == 0:
        return aList[0] + binaryListSort(aList[1:])
    else:
        return binaryListSort(aList[1:]) + aList[0]

【问题讨论】:

  • 你说的是哪种编程语言?
  • python 抱歉,感谢您的关注!

标签: python list python-3.x indexing


【解决方案1】:

这似乎根本没有进行任何排序。您所做的只是检查列表的第一个元素是否为 0,然后切掉第一个元素并再次检查。如果它从不为 0,最终它会尝试检查空列表的第一个元素,从而导致错误。

【讨论】:

  • 我认为它正在尝试排序。我花了一段时间才想到“二进制整数”可能是什么,但如果列表的唯一条目是 0 和 1,它应该可以工作。如果 OP 处理空列表的情况,并且 OP 修复了代码,因此它不会尝试将整数添加到列表中。
【解决方案2】:

在每次递归中,你会将列表长度减 1,所以你会得到一个长度为 1 的空列表,所以当你使用 aList[1:] 时,它会抛出 indexerror。你应该认为 aList 是空列表。

你可以用一个例子来测试,你可以使用下面的代码,它会很好。

def binaryListSort(aList):
    '''takes a list of binary numbers and puts them in ascending order
    inputs: a list of binary integers, aList Outputs: a new list with numbers
    in ascending order.'''

    if len(aList) == 0:
      return

    if len(aList) == 1:
      return aList

    if aList[0] == 0:
      return [aList[0]] + binaryListSort(aList[1:])
    else:
      return binaryListSort(aList[1:]) + [aList[0]]

【讨论】:

  • 此代码不起作用,因为您不能将整数添加到列表中。
  • 是的,你是对的,我没有注意到。我现在已经解决了这个问题。
【解决方案3】:

通过这个循环,您最终将使用仅包含 1 个项目的列表调用 binaryListSort。然后是 aList[1] 未定义,因此 aList[1:] 将导致 indexerror 如果 aList 的长度为 1,您需要将代码插入到将返回 aList 的白行中。

【讨论】:

  • 切片永远不会出现索引错误。如果列表的长度小于一个元素,切片 [1:] 只会给出一个空列表。当代码随后访问元素 0 时出现索引错误。
  • 我确实很糟糕。不过问题会通过添加代码if len(aList) == 1: return aList解决
猜你喜欢
  • 1970-01-01
  • 2020-10-11
  • 1970-01-01
  • 2023-02-22
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多