gpt4 book ai didi

python - Python3 中的列表索引是如何工作的?

转载 作者:行者123 更新时间:2023-12-01 01:12:43 25 4
gpt4 key购买 nike

假设我们有

a = [1, 2, 3]

每当我在列表中使用索引时,如 0 , 1 , 2在这种情况下,python3如何通过知道索引来检索元素?除了索引之外,列表中的每个元素是否有任何特定的地址?

最佳答案

从技术上讲,数组(Python 中的列表)存储的是指针而不是对象本身,这使得数组只能包含特定大小的元素,即使是 Python 中的混合类型列表也是如此。

来自 python 文档:

CPython’s lists are really variable-length arrays, not Lisp-style linked lists. The implementation uses a contiguous array of references to other objects, and keeps a pointer to this array and the array’s length in a list head structure.

This makes indexing a list a[i] an operation whose cost is independent of the size of the list or the value of the index.

When items are appended or inserted, the array of references is resized. Some cleverness is applied to improve the performance of appending items repeatedly; when the array must be grown, some extra space is allocated so the next few times don’t require an actual resize.

来源: https://docs.python.org/3/faq/design.html#how-are-lists-implemented-in-cpython

更多说明:

<小时/>

什么是指针?

指针是存储内存地址的变量。指针用于存储其他变量或内存项的地址。

索引如何工作?

当 p 表示指向数组第一个元素的指针时,

a[i] 与 (p + i) 含义相同:*(a+i)因此,如果指针 p 指向数组的一个元素,则将 n 添加到该指针使其指向原始元素之后的第 n 个元素。这涉及在对象之间添加或减去正确的偏移量(基于引用的大小)(以字节为单位)。

引用的大小与 CPU 的字大小相同 32 位系统上为 4 字节,64 位系统上为 8 字节

memory representation of array of pointers

希望你能明白这一点..这是我在 stackoverflow 上的第一个回答,如果有帮助的话请投票。谢谢。

关于python - Python3 中的列表索引是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54688421/

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