Python:列表的每个元素占用多少空间? [英] Python: How much space does each element of a list take?

查看:369
本文介绍了Python:列表的每个元素占用多少空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个非常大的列表,并且正在尝试弄清楚我可以将其扩展多大,以便它仍然适合1-2GB的RAM.我正在64位(x86_64)上使用CPython实现.

I need a very large list, and am trying to figure out how big I can make it so that it still fits in 1-2GB of RAM. I am using the CPython implementation, on 64 bit (x86_64).

感谢bua的回答,我填写了一些更具体的答案.

(以字节为单位)的空间(内存)使用量是什么?

What is the space (memory) usage of (in bytes):

  • 列表本身
    • sys.getsizeof([]) == 72
    • the list itself
      • sys.getsizeof([]) == 72
      • sys.getsizeof([0, 1, 2, 3]) == 104,因此每个条目8个字节的开销.
      • sys.getsizeof([0, 1, 2, 3]) == 104, so 8 bytes overhead per entry.
      • sys.getsizeof(2**62) == 24(但根据整数大小而有所不同)
      • sys.getsizeof(2**63) == 40
      • sys.getsizeof(2**128) == 48
      • sys.getsizeof(2**256) == 66
      • sys.getsizeof(2**62) == 24 (but varies according to integer size)
      • sys.getsizeof(2**63) == 40
      • sys.getsizeof(2**128) == 48
      • sys.getsizeof(2**256) == 66
      • sys.getsizeof(C()) == 72(C是一个空的用户空间对象)
      • sys.getsizeof(C()) == 72 (C is an empty user-space object)

      如果您可以共享有关观察到的尺寸的更多常规数据,那将是很好的.例如:

      If you can share more general data about the observed sizes, that would be great. For example:

      • 是否存在特殊情况(我认为可能共享不可变的值,因此,布尔列表可能不会为数据占用任何额外的空间)?
      • 也许小列表占用X字节的开销,而大列表占用Y字节的开销?

      推荐答案

      指向起点:

      >>> import sys
      >>> a=list()
      >>> type(a)
      <type 'list'>
      >>> sys.getsizeof(a)
      36
      >>> b=1
      >>> type(b)
      <type 'int'>
      >>> sys.getsizeof(b)
      12
      

      以及来自python帮助:

      and from python help:

      >>> help(sys.getsizeof)
      Help on built-in function getsizeof in module sys:
      
      getsizeof(...)
          getsizeof(object, default) -> int
      
          Return the size of object in bytes.
      

      这篇关于Python:列表的每个元素占用多少空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆