当我要求它给出 -1 的值时,Python 给了我列表的最后一个值

Pyt*_*Pro -4 python python-3.7

我在 python 3.7.1 上。

我正在处理数据结构,在使用列表时,我遇到了一个错误。当我尝试访问索引 -1 时,python 给了我列表中的最后一个条目。

我打开了 python shell,并运行了以下命令:

>>> l = [0,1,2]
>>> l[-1]
2
>>> l[3]
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    l[3]
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

这可能是由于 python 3.7.1 上的一个错误,但是除了更新 python 之外还有其他方法可以解决这个问题吗?我正在做一个项目。

小智 5

负指数意味着您从右侧而不是左侧开始计数。所以 l[-1] 访问数组中的最后一个索引,l[-2] 访问倒数第二个,依此类推。

l[3] 不起作用,因为您的索引为 0、1 和 2,没有 3。