您的位置:首页 > 其它

删除list中元素的问题

2014-06-12 11:02 183 查看
先来看一个例子:

lst = [x for x in xrange(10)];
print(lst)
for x in lst:
lst.remove(x)
print(lst)

结果为:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9] #为啥没有被删除干净呢?


查看python源代码:

Python-2.7.5\Objects\listobject.c 【python中list的实现代码】

remove方法对应的代码如下:

static PyObject *
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 (<span style="background-color: rgb(51, 255, 51);">list_ass_slice(self, i, i+1,</span>
<span style="color:#000000;background-color: rgb(51, 255, 51);">(PyObject *)NULL) == 0</span>)
Py_RETURN_NONE;
return NULL;
}
else if (cmp < 0)
return NULL;
}
PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
return NULL;
}

代码逻辑比较简单,先查找是否存在要被remove的元素,如果存在多个相同的值,只remove第一个被找到的元素。

找到之后,就调用list_ass_slice(self, i, i+1,(PyObject *)NULL) == 0

 

再看这个list_ass_slice函数中干了什么,如下片段:

if (d < 0) { /* Delete -d items */
memmove(&item[ihigh+d], &item[ihigh],
(Py_SIZE(a) - ihigh)*sizeof(PyObject *));
list_resize(a, Py_SIZE(a) + d);
item = a->ob_item;
}

原来是将要被删除之后的所有元素向前移动。

这就能解释为啥开始的例子中,遍历remove后,仍然还有元素没有remove掉了。因为remove掉2之后,元素3跑到了2的位置,下一个被遍历的就变成4了。

PS:python的list本身就是一个指针数组:

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;


总结:

1、如果要删除list中的所有元素,可以使用clear方法;

2、不建议删除list中的部分元素,因为需要移动被删除元素后面的所有元素,效率比较低;

可以将需要删除的元素置为None,后续处理时过滤掉None即可。

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: