python - python 列表中可以跳过索引吗?

标签 python list

假设我有一个 len(list) == 5

的列表

我可以确定 list[4] 存在吗?

或者也许一个项目可以被删除,然后列表将具有索引 0,1,2,3,5,其长度为 5 但没有索引 4?

最佳答案

Can I be sure list[4] exists?

是的,你可以。如果 len(list) 返回 5,则您 100% 确定列表中有 5 个元素。

Or maybe an item could get deleted and then the list would have indices 0,1,2,3,5 which would have length 5 but without index 4?

同样,如果 len(list) 返回 5,则列表中有 5 个元素。因为列表在 python 中是从零开始的,所以 list[4] 将是列表的最后一个元素

这里引用 python documentation :

Operation: s[i]

Result: ith item of s

Notes: origin 0

您也可以在 REPL(python 语言 shell)中尝试,正如 Jim 在他的 answer 中所示。 。如果您创建一个包含 5 个元素的列表,len 将返回 5。如果您删除列表中的任何元素,例如第 4 个元素,那么 len 现在将返回 4,并且您将访问最后一个元素(即第 5 个元素)删除之前)使用 list[4]

关于python - python 列表中可以跳过索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49410978/

相关文章:

python -docx 从word docx中提取表格

python - 为什么复制的字典指向同一个目录而列表却没有?

c# - 按对象的属性对 List 中的对象进行排序

python - 列表上的总和可能更快

python - 如何更改 PySide2 中图表的颜色

python - Django 设置.py 错误 : Import by filename is not supported

python - SQLAlchemy:是否知道模型对象的字段名称和值?

python - 为什么空字符串计数 ("") 返回比目标字符串长度大 1 的计数?

python - 使用 Python 从字符串列表自动生成文档标题

algorithm - 在排序和旋转列表中插入一个元素