如果我有10个元素的列表:
>>> l = [1,2,3,4,5,6,7,8,9,0]
Run Code Online (Sandbox Code Playgroud)
为什么l [10]会返回一个IndexError,但是l [-1]会返回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
Run Code Online (Sandbox Code Playgroud)
我想要做的是如果列表中没有先前的元素则抛出错误.
Gar*_*tty 19
在Python中,否定列表索引表示从列表右侧开始计算的项目(即,l[-n]是简写l[len(l)-n]).
如果您发现需要负指数来指示错误,那么您可以简单地检查该情况并自行引发异常(或者随后处理它):
index = get_some_index()
if index < 0:
raise IndexError("negative list indices are considered out of range")
do_something(l[index])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5961 次 |
| 最近记录: |