本文将介绍列表在 CPython中的实现,因为毕竟Cpython 又是 Python 最为常用的实现。

Python 中的列表非常强大,看看它的内部实现机制是怎么样的,一定非常有趣。

下面是一段 Python 脚本,在列表中添加几个整数,然后打印列表。

>>> l = []

>>> l.append(1)

>>> l.append(2)

>>> l.append(3)

>>> l

[1, 2, 3]

>>> for e in l:

...   print e

...

1

2

3

可以发现,列表是一个迭代器。

列表对象的 C 语言结构体

Cpython 中的列表实现类似于下面的 C 结构体。ob_item 是指向列表对象的指针数组。allocated 是申请内存的槽的个数。

typedef struct {

PyObject_VAR_HEAD

PyObject **ob_item;

Py_ssize_t allocated;

} PyListObject;

列表初始化

看看初始化一个空列表的时候发生了什么,例如:l = []。

arguments: size of the list = 0

returns: list object = []

PyListNew:

nbytes = size * size of global Python object = 0

allocate new list object

allocate list of pointers (ob_item) of size nbytes = 0

clear ob_item

set list's allocated var to 0 = 0 slots

return list object

要分清列表大小和分配的槽大小,这很重要。列表的大小和 len(l) 的大小相同。分配槽的大小是指已经在内存中分配了的槽空间数。通常分配的槽的大小要大于列表大小,这是为了避免每次列表添加元素的时候都调用分配内存的函数。下面会具体介绍。

Append 操作

向列表添加一个整数:l.append(1) 时发生了什么?调用了底层的 C 函数 app1()。

arguments: list object, new element

returns: 0 if OK, -1 if not

app1:

n = size of list

call list_resize() to resize the list to size n+1 = 0 + 1 = 1

list[n] = list[0] = new element

return 0

下面是 list_resize() 函数。它会多申请一些内存,避免频繁调用 list_resize() 函数。列表的增长模式为:0,4,8,16,25,35,46,58,72,88……

arguments: list object, new size

returns: 0 if OK, -1 if not

list_resize:

new_allocated = (newsize >> 3) + (newsize

new_allocated += newsize = 3 + 1 = 4

resize ob_item (list of pointers) to size new_allocated

return 0

现在分配了 4 个用来装列表元素的槽空间,并且第一个空间中为整数 1。如下图显示 l[0] 指向我们新添加的整数对象。虚线的方框表示已经分配但没有使用的槽空间。

列表追加元素操作的平均复杂度为 O(1)。

继续添加新的元素:l.append(2)。调用 list_resize 函数,参数为 n+1 = 2, 但是因为已经申请了 4

个槽空间,所以不需要再申请内存空间。再添加两个整数的情况也是一样的:l.append(3),l.append(4)。下图显示了我们现在的情况。

Insert 操作

在列表偏移量 1 的位置插入新元素,整数 5:l.insert(1,5),内部调用ins1() 函数。

arguments: list object, where, new element

returns: 0 if OK, -1 if not

ins1:

resize list to size n+1 = 5 -> 4 more slots will be allocated

starting at the last element up to the offset where, right shift each element

set new element at offset where

return 0

虚线的方框依旧表示已经分配但没有使用的槽空间。现在分配了 8 个槽空间,但是列表的大小却只是 5。

列表插入操作的平均复杂度为 O(n)。

Pop 操作

取出列表最后一个元素 即l.pop(),调用了 listpop() 函数。在 listpop() 函数中会调用 list_resize 函数,如果取出元素后列表的大小小于分配的槽空间数的一半,将会缩减列表的大小。

arguments: list object

returns: element popped

listpop:

if list empty:

return null

resize list with size 5 - 1 = 4. 4 is not less than 8/2 so no shrinkage

set list object size to 4

return last element

列表 pop 操作的平均复杂度为 O(1)。

可以看到 pop 操作后槽空间 4 依然指向原先的整数对象,但是最为关键的是现在列表的大小已经变为 4。

继续 pop 一个元素。在 list_resize() 函数中,size – 1 = 4 – 1 = 3 已经小于所分配的槽空间大小的一半,所以缩减分配的槽空间为 6,同时现在列表的大小为 3。

可以看到槽空间 3 和 4 依然指向原先的整数,但是现在列表的大小已经变为 3。

Remove 操作

Python 的列表对象有个方法,删除指定的元素: l.remove(5)。底层调用 listremove() 函数。

arguments: list object, element to remove

returns none if OK, null if not

listremove:

loop through each list element:

if correct element:

slice list between element's slot and element's slot + 1

return none

return null

为了做列表的切片并且删除元素,调用了 list_ass_slice() 函数,它的实现方法比较有趣。我们在删除列表位置 1 的元素 5 的时候,低位的偏移量为 1 同时高位的偏移量为 2.

arguments: list object, low offset, high offset

returns: 0 if OK

list_ass_slice:

copy integer 5 to recycle list to dereference it

shift elements from slot 2 to slot 1

resize list to 5 slots

return 0

列表 remove 操作的复杂度为 O(n)。

作者:佚名

来源:51CTO

python list 底层_深入Python列表的内部实现相关推荐

  1. python核心底层_大话Python函数底层逻辑 - 北门吹雪 - 开发者的网上家园

    函数 叫 子过程或子程序 描叙的更为贴近实际应用场景 这和数学中的函数实现上不同但语义上相识,如 f(x) = expressiom, 给定一个确定的输入必然返回一个确定的输出 数学中函数的关系是通过 ...

  2. python 概率分布模型_使用python的概率模型进行公司估值

    python 概率分布模型 Note from Towards Data Science's editors: While we allow independent authors to publis ...

  3. python 时间序列预测_使用Python进行动手时间序列预测

    python 时间序列预测 Time series analysis is the endeavor of extracting meaningful summary and statistical ...

  4. python高斯求和_利用Python进行数据分析(3)- 列表、元组、字典、集合

    本文主要是对Python的数据结构进行了一个总结,常见的数据结构包含:列表list.元组tuple.字典dict和集合set. image 索引 左边0开始,右边-1开始 通过index()函数查看索 ...

  5. python 字节流分段_由Python历史「解密」Python底层逻辑

    一次纯粹的hacking Python的作者,Guido von Rossum,荷兰人.1982年,Guido从阿姆斯特丹大学获得了数学和计算机硕士学位.尽管,他算得上是一位数学家,但他更加享受计算机 ...

  6. python queue 调试_学Python不是盲目的,是有做过功课认真去了解的

    有多少伙伴是因为一句'人生苦短,我用Python'萌生想法学Python的!我跟大家更新过很多Python学习教程普及过多次的Python相关知识,不过大家还是还得计划一下Python学习路线!Pyt ...

  7. python医学图像读取_对python读取CT医学图像的实例详解

    需要安装OpenCV和SimpleItk. SimpleItk比较简单,直接pip install SimpleItk即可. 代码如下: #coding:utf-8 import SimpleITK ...

  8. python集群_使用Python集群文档

    python集群 Natural Language Processing has made huge advancements in the last years. Currently, variou ...

  9. python机器学习预测_使用Python和机器学习预测未来的股市趋势

    python机器学习预测 Note from Towards Data Science's editors: While we allow independent authors to publish ...

最新文章

  1. python3 pymysql 查询结果转字典dict
  2. 简单Unity时间架构设计(克洛诺斯之匙)
  3. IDEA中实用的快捷方式
  4. vue cli vue 3.x
  5. 关于多条id相同,只取其中一条记录的sql语句
  6. python抓资源_python3 抓取网页资源的 N 种方法
  7. 关于OpenCV的基本数据类型
  8. 电力设计手册_电气设计负荷计算方法
  9. java mvc页面传值方式_详解SpringMVC的ModelAndView传值方法
  10. 修改现有用户帐户的 Microsoft Lync Server 2010 属性
  11. 【博客迁移】hyrepo.com
  12. JSTL流程控制操作--c:if,c:choose,c:when,c:other
  13. 双系统如何干净删除Ubuntu
  14. C# XmlDocument.Save文件操作System.IO.IOException:The process cannot access the file because it is being
  15. QQ昵称修改颜色,彩色昵称太酷了
  16. 艾德莱斯绸:“千年时尚”托起新产业
  17. mac 时间机器备份慢? 首次备份限速解除!
  18. 基于Linux的音乐音效软件,在Arch Linux系统上可用Pipewire取代PulseEffects音效软件
  19. BZOJ 1038 瞭望塔(半平面交)
  20. js(Mandango:壮汉专用,电影院划位工具)

热门文章

  1. weblogic部署,常见错误解决二——ClassCastException
  2. 飞鸽传书,又见飞鸽传书,
  3. 飞鸽传书,去看了下WEBBROWSER的资料
  4. Windows 文件含义大全
  5. “大龄”程序员的出路
  6. eclipse中的java包awt_Eclipse中打包java程序
  7. transition属性详细讲解
  8. 服务器虚拟化svc,SVC的虚拟化变革
  9. 非x面容解锁插件ios13_iOS13.5 Beta3 推送,戴口罩解锁更加方便
  10. Caret模型训练和调参更多参数解读(2)