Python 清單實作:解開謎團
Python 清單是該語言的一個組成部分,用於儲存任何類型元素的集合。許多開發人員對其底層實作進行了猜測,但最終的答案仍然難以捉摸。本文深入研究 Python 的 C 程式碼,揭開清單實現背後的真相。
透過檢查頭檔 listobject.h,我們發現了 Python 清單的基本結構:
typedef struct { PyObject_HEAD Py_ssize_t ob_size; /* 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 */ Py_ssize_t allocated; } PyListObject;
這段程式碼顯示Python列表確實是作為向量或陣列實現的。具體來說,它們利用過度分配策略,這意味著提前分配記憶體以用於清單中的潛在添加。
如果清單達到其分配的限制,listobject.c 中的調整大小代碼將透過分配來擴展數組:
new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6); new_allocated += newsize;
其中newsize 表示請求的大小,無論是擴展任意數量的元素還是簡單地附加一。
此外,Python 常見問題解答提供了有關清單實現的更多見解,突出了其動態和高效的性質,能夠根據需要調整大小,同時保持效能。
以上是Python 內部如何實作列表?的詳細內容。更多資訊請關注PHP中文網其他相關文章!