推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
phoolean
V2EX  ›  Python

Python 的 list 中的元素是像 C 的数组那样在内存里顺序存放的吗?

  •  
  •   phoolean · Apr 29, 2019 · 3949 views
    This topic created in 2570 days ago, the information mentioned may be changed or developed.
    9 replies    2019-04-30 18:11:09 +08:00
    BBCCBB
        1
    BBCCBB  
       Apr 29, 2019
    它支持随机访问,很明显是。
    Sasasu
        2
    Sasasu  
       Apr 29, 2019
    不,list 保存的是指针。
    vencent
        3
    vencent  
       Apr 29, 2019
    首先,保存的是对象的引用,不是对象。
    其次,list 是动态数组。
    sujin190
        4
    sujin190  
       Apr 29, 2019
    底层数据结构是的,只不过数组保存的是 object 指针,所以相比 c,即使保存数字这样的基础数据结构,仍然需要一次额外内存访问

    可以动态增长是每次分配数组内存都是 2 的倍数,有额外空间,空间不足 resize 会申请一个新内存,然后 copy 过去,不过保存指针在数组值是大对象 resize 时性能又影响不那么大了
    chitanda
        5
    chitanda  
       Apr 29, 2019 via Android
    panda 才是这样的吧
    xpresslink
        6
    xpresslink  
       Apr 29, 2019
    i0error
        7
    i0error  
       Apr 30, 2019 via iPhone
    可以随时 append,我猜不是。。。
    ccdrea
        8
    ccdrea  
       Apr 30, 2019
    >>> a = 1
    >>> id(a)
    1598830848
    >>> b = [a]
    >>> id(b)
    9390640
    >>> id(b[0])
    1598830848
    >>>
    看懂了吗
    zpoint
        9
    zpoint  
       Apr 30, 2019
    是一个 c 数组, 但是数组里面的每个元素都是指向 PyObject 的指针, 达到一定阈值会触发 增大 /缩小 的操作, 实现上和 c++ 的 std::vector 类似

    参考: https://github.com/zpoint/Cpython-Internals/blob/master/BasicObject/list/list.md
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1534 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 48ms · UTC 16:47 · PVG 00:47 · LAX 09:47 · JFK 12:47
    ♥ Do have faith in what you're doing.