IndexError:列出索引超出范围和python [英] IndexError: list index out of range and python

查看:26
本文介绍了IndexError:列出索引超出范围和python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我告诉我的程序打印输出的第 53 行.这个错误是不是告诉我没有那么多行,因此无法打印出来?

解决方案

如果你有一个包含 53 个项目的列表,最后一个是 thelist[52] 因为索引从 0 开始.


来自 真正的 Python:了解 Python 回溯 - IndexError:

<块引用>

索引错误

IndexError 在您尝试从序列中检索索引时引发,例如 listtuple,并且索引不是'在序列中找不到.Python 文档定义了何时引发此异常:

<块引用>

当序列下标超出范围时引发.(来源)

这是一个引发 IndexError 的例子:

test = list(range(53))测试[53]---------------------------------------------------------------------------IndexError 回溯(最近一次调用最后一次)<ipython-input-6-7879607f7f36>在<模块>1 测试 = 列表(范围(53))---->2 测试[53]IndexError:列表索引超出范围

<块引用>

IndexError 的错误消息行并没有为您提供很好的信息.您可以看到您有一个 out of range 的序列引用以及序列的类型是什么,在本例中为 list.该信息与回溯的其余部分相结合,通常足以帮助您快速确定如何解决问题.

I'm telling my program to print out line 53 of an output. Is this error telling me that there aren't that many lines and therefore can not print it out?

解决方案

If you have a list with 53 items, the last one is thelist[52] because indexing starts at 0.


From Real Python: Understanding the Python Traceback - IndexError:

IndexError

The IndexError is raised when you attempt to retrieve an index from a sequence, like a list or a tuple, and the index isn’t found in the sequence. The Python documentation defines when this exception is raised:

Raised when a sequence subscript is out of range. (Source)

Here’s an example that raises the IndexError:

test = list(range(53))
test[53]

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-7879607f7f36> in <module>
      1 test = list(range(53))
----> 2 test[53]

IndexError: list index out of range

The error message line for an IndexError doesn’t give you great information. You can see that you have a sequence reference that is out of range and what the type of the sequence is, a list in this case. That information, combined with the rest of the traceback, is usually enough to help you quickly identify how to fix the issue.

这篇关于IndexError:列出索引超出范围和python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆