python - 索引运算符

标签 python python-3.x

谁能给我解释一下原因:

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 or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

大多数实现序列协议(protocol)的第三方类型的行为方式相同,但请注意它们有义务 - 这只是内置序列的保证行为。

关于python - 索引运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23168600/

相关文章:

python - Django:为什么这个简单的标签不起作用?

python-3.x - 为什么我会收到错误 "ClientConnectorError"?

python - 使用 python 解析 SQL 以提取列名和表名

python - PyQT 在调用其他函数之前强制更新 textEdit

python - 如何在 python3 中取消使用 __setitem__ 验证的 'dict' 的子类?

python - 如何将换行符添加到 file.write() 的末尾?

python-3.x - Python 检查 SQLite3 中是否存在

python - 在带有标记文本的 altair 中对条形图进行排序时出现问题

python - float 、小数、价格和部分数量

python - Pip安装日志在哪里?