谁能给我解释一下原因:
print(my_list[-1])
等同于:
print (my_list[len(my_list) - 1])
这又是如何避免写作的捷径
len(my_list)
谢谢
最佳答案
之所以如此,纯粹是因为 Python 将其定义为如此。负索引被视为从列表(或字符串或元组)的末尾开始计数,而不是从开头开始计数。引用the docs ,引用my_list[i]
,以及扩展形式my_list[i:j]
和my_list[i:j:k]
:
If
i
orj
is negative, the index is relative to the end of the string:len(s) + i
orlen(s) + j
is substituted. But note that -0 is still 0.
大多数实现序列协议(protocol)的第三方类型的行为方式相同,但请注意它们有义务 - 这只是内置序列的保证行为。
关于python - 索引运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23168600/