清除清单的不同方法 [英] Different ways of clearing lists
本文介绍了清除清单的不同方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当您想在Python中清除列表时,有什么理由要做比这两行之一更复杂的事情吗?
Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python?
old_list = []
old_list = list()
我问的原因是我只是在一些正在运行的代码中看到了这一点:
The reason I ask is that I just saw this in some running code:
del old_list[ 0:len(old_list) ]
推荐答案
清除列表将影响同一列表的所有其他引用.
Clearing a list in place will affect all other references of the same list.
例如,此方法不会影响其他引用:
For example, this method doesn't affect other references:
>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]
但是这个确实做到了:
>>> a = [1, 2, 3]
>>> b = a
>>> del a[:] # equivalent to del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True
您也可以这样做:
>>> a[:] = []
这篇关于清除清单的不同方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文