gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:48 24 4
gpt4 key购买 nike

假设我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com