如何清空列表?

问题:如何清空列表?

用这种方式清空列表似乎太“脏”了:

while len(alist) > 0 : alist.pop()

是否存在明确的方法?

It seems so “dirty” emptying a list in this way:

while len(alist) > 0 : alist.pop()

Does a clear way exist to do that?


回答 0

实际上,这将从列表中删除内容,但不会用新的空列表替换旧标签:

del lst[:]

这是一个例子:

lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)

为了完整起见,切片分配具有相同的效果:

lst[:] = []

它也可以用于缩小列表的一部分,同时替换一部分(但这超出了问题的范围)。

请注意,这样lst = []做不会清空列表,只是创建一个新对象并将其绑定到变量lst,但是旧列表仍将具有相同的元素,并且如果具有其他变量绑定,效果将显而易见。

This actually removes the contents from the list, but doesn’t replace the old label with a new empty list:

del lst[:]

Here’s an example:

lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)

For the sake of completeness, the slice assignment has the same effect:

lst[:] = []

It can also be used to shrink a part of the list while replacing a part at the same time (but that is out of the scope of the question).

Note that doing lst = [] does not empty the list, just creates a new object and binds it to the variable lst, but the old list will still have the same elements, and effect will be apparent if it had other variable bindings.


回答 1

如果你正在运行的Python 3.3或更好的,你可以使用clear()的方法list,这是平行clear()dictsetdeque和其他易变的容器类型:

alist.clear()  # removes all items from alist (equivalent to del alist[:])

按照链接的文档页面,也可以使用来实现相同的目的alist *= 0

总结起来,有四种等效的方法可以就地清除列表(与PythonZen完全相反!):

  1. alist.clear() # Python 3.3+
  2. del alist[:]
  3. alist[:] = []
  4. alist *= 0

If you’re running Python 3.3 or better, you can use the clear() method of list, which is parallel to clear() of dict, set, deque and other mutable container types:

alist.clear()  # removes all items from alist (equivalent to del alist[:])

As per the linked documentation page, the same can also be achieved with alist *= 0.

To sum up, there are four equivalent ways to clear a list in-place (quite contrary to the Zen of Python!):

  1. alist.clear() # Python 3.3+
  2. del alist[:]
  3. alist[:] = []
  4. alist *= 0

回答 2

您可以尝试:

alist[:] = []

这意味着:在[]位置[:](从头到尾的所有索引)的列表(0个元素)中拼接

[:]是切片运算符。有关更多信息,请参见此问题

You could try:

alist[:] = []

Which means: Splice in the list [] (0 elements) at the location [:] (all indexes from start to finish)

The [:] is the slice operator. See this question for more information.


回答 3

事实证明,使用python 2.5.2的del l[:]速度比l[:] = []使用1.1 usec的速度略慢。

$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2

it turns out that with python 2.5.2, del l[:] is slightly slower than l[:] = [] by 1.1 usec.

$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2

回答 4

lst *= 0

与…具有相同的效果

lst[:] = []

它稍微简单一些,也许更容易记住。除此之外,无话可说

效率似乎差不多

lst *= 0

has the same effect as

lst[:] = []

It’s a little simpler and maybe easier to remember. Other than that there’s not much to say

The efficiency seems to be about the same


回答 5

list = []

将重置list为空列表。

请注意,通常您不应该遮盖保留的函数名称,例如list,它是列表对象的构造函数- 例如,可以使用lstlist_代替。

list = []

will reset list to an empty list.

Note that you generally should not shadow reserved function names, such as list, which is the constructor for a list object — you could use lst or list_ instead, for instance.


回答 6

您可以使用的另一个简单代码(取决于您的情况)是:

index=len(list)-1

while index>=0:
    del list[index]
    index-=1

您必须在列表的长度处开始索引,然后相对于索引在0处向前,向后前进,因为这将使您最终获得的索引等于列表的长度,并且仅将其切成两半。

另外,请确保while行上有一个“大于或等于”符号。省略它会使您剩下list [0]。

Another simple code you could use (depending on your situation) is:

index=len(list)-1

while index>=0:
    del list[index]
    index-=1

You have to start index at the length of the list and go backwards versus index at 0, forwards because that would end you up with index equal to the length of the list with it only being cut in half.

Also, be sure that the while line has a “greater than or equal to” sign. Omitting it will leave you with list[0] remaining.