+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1
但是,越界列表/字符串的检查仍然存在:
>>> s = 'Python'
>>> s[6]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> s[-7]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
Python 中的某些类型,如列表和字符串,支持负索引。它们允许您从末尾获取元素:
c[-1]这是最后一个元素,c[-2]倒数第二个,依此类推。可以重写负索引以计算正索引,例如:c[len(c) - 1]等等c[len(c) - 2]。Python 文档有一个直观的图表,显示了字符串中的字符是如何编号的(也适用于列表):
但是,越界列表/字符串的检查仍然存在:
顺便说一句,使用扩展切片语法,您可以通过指定负步幅来反转列表: