在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])
在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])