gpt4 book ai didi

python - 尝试访问第 N 个项目时出现 "IndexError: list index out of range"是否意味着我的列表中的项目少于 N 个?

转载 作者:IT老高 更新时间:2023-10-28 20:56:28 26 4
gpt4 key购买 nike

我告诉我的程序打印输出的第 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 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)

这是一个引发 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.

关于python - 尝试访问第 N 个项目时出现 "IndexError: list index out of range"是否意味着我的列表中的项目少于 N 个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1098643/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com