remove是否在内部复制数组以删除指定的元素?
没有
它是如何工作的?
从pythonsource code for lists,remove()调用listremove():listremove(PyListObject *self, PyObject *v)
{
Py_ssize_t i;
for (i = 0; i < Py_SIZE(self); i++) {
int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
if (cmp > 0) {
if (list_ass_slice(self, i, i+1, (PyObject *)NULL) == 0)
Py_RETURN_NONE;
return NULL;
}
else if (cmp < 0)
return NULL;
}
PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
return NULL;
}
Python在要删除的项的索引处对列表进行切片。我找到了一个对删除函数here的更好的描述:
^{pr2}$
根据你的“到位”概念,我想说这是相当到位的,并且适合你的具体情况。但有人已经提出了一个很好的观点,即在遍历列表时不要修改列表。在