我告诉我的程序打印输出的第 53 行。这个错误是否告诉我没有那么多行,因此无法打印出来?
最佳答案
如果您有一个包含 53 个项目的列表,则最后一个是 thelist[52]
,因为索引从 0 开始。
来自 Real Python: Understanding the Python Traceback - IndexError
:
IndexError
The
IndexError
is raised when you attempt to retrieve an index from a sequence, like alist
or atuple
, 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)
这是一个引发
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 isout of range
and what the type of the sequence is, alist
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.
关于python - 尝试访问第 N 个项目时出现 "IndexError: list index out of range"是否意味着我的列表中的项目少于 N 个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1098643/