为什么 Python 返回否定列表索引? [英] Why does Python return negative list indexes?

查看:45
本文介绍了为什么 Python 返回否定列表索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这个包含 10 个元素的列表:

<预><代码>>>>l = [1,2,3,4,5,6,7,8,9,0]

为什么 l[10] 会返回 IndexError,而 l[-1] 会返回 0?

<预><代码>>>>升[10]回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中IndexError:列表索引超出范围>>>升[0]1>>>升[-1]0>>>升[-2]9

如果列表中没有前面的元素,我想要做的是抛出一个错误.

解决方案

在 Python 中,否定列表索引表示从列表右侧开始计数的项目(即 l[-n] 是简写对于 l[len(l)-n]).

如果您发现需要负索引来指示错误,那么您可以简单地检查该情况并自己引发异常(或当场处理):

index = get_some_index()如果索引<0:raise IndexError("否定列表索引被认为超出范围")做某事(l [索引])

If I have this list with 10 elements:

>>> l = [1,2,3,4,5,6,7,8,9,0]

Why will l[10] return an IndexError, but l[-1] returns 0?

>>> l[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> l[0]
1
>>> l[-1]
0
>>> l[-2]
9

What I want to do is throw an error if there are no previous elements in the list.

解决方案

In Python, negative list indices indicate items counted from the right of the list (that is, l[-n] is shorthand for l[len(l)-n]).

If you find you need negative indices to indicate an error, then you can simply check for that case and raise the exception yourself (or handle it then and there):

index = get_some_index()
if index < 0:
    raise IndexError("negative list indices are considered out of range")
do_something(l[index])

这篇关于为什么 Python 返回否定列表索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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