[英]Find the address of the 2nd element of a list in Python
首先,這個問題只是為了更好地理解 Python 的 memory 管理,我知道指針的使用違背了 Python 的理念。 但我只是想知道我們是否可以做到。
在C中,如果我的理解是正確的,數組變量只是一個指向一系列塊中第一個memory塊的指針。 也就是說,我們可以做以下所有事情:
(以上幾點如有錯誤還請指正)
我的問題是,我們可以在 Python 中實現類似的東西嗎? 據我所知,我們可以:
>>> import ctypes
>>> var = 10
>>> address = id(var)
>>> print(address)
140654547704400
>>> print(ctypes.cast(address, ctypes.py_object).value)
10
但是,這種方法只有在我們處理“簡單”變量時才有效,例如 integer。 如果我聲明一個列表並調用 id():
>>> arr = [1, 1.414, 2.718, 3.141]
>>> id(arr)
140654545282880
>>> id(arr[1])
140654545480880
>>> id(1.414)
140654545480880
我將從id(arr[1])
得到的是 1.414 的地址,而不是列表arr
的第二個元素的地址。 我想要得到的是 140654545282912 = id(arr) + 32。
所以問題是,我們是否有可能找到列表的第二個元素的地址,而不是它在 Python 中引用的變量的地址?
在 Python 中,一切都是 object,甚至像int
這樣的原始數據類型。 如果是list
,這將是具有以下定義的PyListObject :
typedef struct {
PyObject_VAR_HEAD
/* Vector of pointers to list elements. list[0] is ob_item[0], etc. */
PyObject **ob_item;
/* ob_item contains space for 'allocated' elements. The number
* currently in use is ob_size.
* Invariants:
* 0 <= ob_size <= allocated
* len(list) == ob_size
* ob_item == NULL implies ob_size == allocated == 0
* list.sort() temporarily sets allocated to -1 to detect mutations.
*
* Items must normally not be NULL, except during construction when
* the list is not yet visible outside the function that builds it.
*/
Py_ssize_t allocated;
} PyListObject;
正如您在注釋中看到的, ob_item
結構成員保存指向列表元素的指針。
In summary, a list in Python is an object and it's not equivalent to arrays in C where the name of an array can be used as a pointer to the first element in the array so you can do pointer arithmetic.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.