是否出现“IndexError:列表索引超出范围”? 当尝试访问第 N 个项目时意味着我的列表少于 N 个项目?
我告诉我的程序打印输出的第 53 行。 这个错误是否告诉我没有那么多行,因此无法打印出来?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您有一个包含 53 项的列表,则最后一项是
thelist[52]
,因为索引从 0 开始。来自 真正的 Python:了解 Python 回溯 -
IndexError
: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
:是的,
您正在尝试访问列表中不存在的元素。
你有过差一错误吗?
Yes,
You are trying to access an element of the list that does not exist.
Have you got an off-by-one error?
Python 索引的工作方式是从 0 开始,因此列表的第一个数字将为 [0]。 你必须打印[52],因为起始索引是0并且
因此第 53 行是
[52]
。从该值中减去 1 就应该没问题了。 :)
The way Python indexing works is that it starts at 0, so the first number of your list would be [0]. You would have to print[52], as the starting index is 0 and
therefore line 53 is
[52]
.Subtract 1 from the value and you should be fine. :)
是的。 该序列没有第 54 项。
Yes. The sequence doesn't have the 54th item.
这是正确的。 “列表索引超出范围”很可能意味着您正在引用列表的第 n 个元素,而列表的长度小于 n。
That's right. 'list index out of range' most likely means you are referring to
n-th
element of the list, while the length of the list is smaller thann
.当您想要克服此错误时,请始终记住,索引和范围的默认值从 0 开始,因此如果总项目数为 100,则 l[99] 和 range(99) 将允许您访问最后一个元素。
每当您遇到此类错误时,请交叉检查范围之间/中间的项目,并确保它们的索引不是最后一个,如果您获得输出,那么您已经犯了上述完美错误。
Always keep in mind when you want to overcome this error, the default value of indexing and range starts from 0, so if total items is 100 then l[99] and range(99) will give you access up to the last element.
whenever you get this type of error please cross check with items that comes between/middle in range, and insure that their index is not last if you get output then you have made perfect error that mentioned above.
如果您从文本文件中读取列表,您可能会得到最后一个空行作为列表元素。
你可以像这样摆脱它:
If you read a list from text file, you may get the last empty line as a list element.
You can get rid of it like this: