获取列表索引的内存位置。不是值位置而是列表索引位置

时间:2017-11-30 15:18:42

标签: python python-3.x list heap-memory

据我所知,Python将Lists存储为内存中的“数组”;但是,“array”存储指向List中PyObject的指针。

我正在使用hex(id(...))来查看列表的内存地址以及列表中的所有项目。但我也希望看到“数组”位置的内存位置。

到目前为止,这是我的翻译代码......

>>> def memory_locations_of(value):
        for index, element in enumerate(value):
            print("{: <15}{}\n{: <15}{}\n".format("index[" + str(index) + "] ", hex(id(element)), str(element), hex(id(str(element)))))

>>> a = ["hello", "world", "!", "!"]
>>> a
['hello', 'world', '!', '!']

>>> memory_locations_of(a)
index[0]       0x34b4bc0
hello          0x34b4bc0
index[1]       0x4053dc0
world          0x4053dc0
index[2]       0x3616620
!              0x3616620
index[3]       0x3616620
!              0x3616620

>>> a[0] = "Hello"
>>> a
['Hello', 'world', '!', '!']

>>> memory_locations_of(a)
index[0]       0x406e260
Hello          0x406e260
index[1]       0x4053dc0
world          0x4053dc0
index[2]       0x3616620
!              0x3616620
index[3]       0x3616620
!              0x3616620

>>> hex(id(a))
'0x3f7cc10'

最后两行是我想要的最接近的内存位置。该内存位置是实际List的位置。那也应该是实际a [0]位置的位置(或非常靠近它)。我还想获得1,a [2]和[3]的真实位置。它基于我的代码,它们应该在'0x3f7cc10' + "index_offset"

是否有一种简单的方法可以解决这个问题,还是设计得很好?

0 个答案:

没有答案
相关问题