不,list.pop 方法不能通过 PyListObjects 上的 C-API 直接使用。
鉴于 list.pop 已经存在并用 C 实现,您可以简单地查看 CPython 实现的作用:
static PyObject *
list_pop_impl(PyListObject *self, Py_ssize_t index)
{
PyObject *v;
int status;
if (Py_SIZE(self) == 0) {
/* Special-case most common failure cause */
PyErr_SetString(PyExc_IndexError, "pop from empty list");
return NULL;
}
if (index < 0)
index += Py_SIZE(self);
if (index < 0 || index >= Py_SIZE(self)) {
PyErr_SetString(PyExc_IndexError, "pop index out of range");
return NULL;
}
v = self->ob_item[index];
if (index == Py_SIZE(self) - 1) {
status = list_resize(self, Py_SIZE(self) - 1);
if (status >= 0)
return v; /* and v now owns the reference the list had */
else
return NULL;
}
Py_INCREF(v);
status = list_ass_slice(self, index, index+1, (PyObject *)NULL);
if (status < 0) {
Py_DECREF(v);
return NULL;
}
return v;
}
Source for CPython 3.7.2
这包括许多 C 扩展无法(轻松)访问的函数,它还处理从特定索引(甚至是负数)弹出。就我个人而言,我什至不会费心重新实现它,只需使用 PyObject_CallMethod 调用 pop 方法:
PyObject *
list_pop(PyObject *lst){
return PyObject_CallMethod(lst, "pop", "n", Py_SIZE(lst) - 1);
}
它可能比重新实现慢一点,但它应该“更安全” - 不能不小心弄乱列表对象的不变量(例如调整大小条件)。
另一个实现存在于Cython
static CYTHON_INLINE PyObject* __Pyx_PyList_Pop(PyObject* L) {
/* Check that both the size is positive and no reallocation shrinking needs to be done. */
if (likely(PyList_GET_SIZE(L) > (((PyListObject*)L)->allocated >> 1))) {
Py_SIZE(L) -= 1;
return PyList_GET_ITEM(L, PyList_GET_SIZE(L));
}
return CALL_UNBOUND_METHOD(PyList_Type, "pop", L);
}
这也可以根据您的用例进行调整。