不同的清单方式 [英] Different ways of clearing lists
本文介绍了不同的清单方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当您想在 Python 中清除列表时,是否有任何理由执行比这两行中的任何一行更复杂的操作?
old_list = []old_list = 列表()
我问的原因是我刚刚在一些正在运行的代码中看到了这一点:
del old_list[ 0:len(old_list) ]
解决方案
就地清除列表将影响同一列表的所有其他引用.
例如,此方法不会影响其他引用:
<预><代码>>>>a = [1, 2, 3]>>>乙 = 一>>>a = []>>>打印(一)[]>>>打印(b)[1, 2, 3]但是这个可以:
<预><代码>>>>a = [1, 2, 3]>>>乙 = 一>>>del a[:] # 等价于 del a[0:len(a)]>>>打印(一)[]>>>打印(b)[]>>>a 是 b真的你也可以这样做:
<预><代码>>>>[:] = []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]
But this one does:
>>> a = [1, 2, 3]
>>> b = a
>>> del a[:] # equivalent to del a[0:len(a)]
>>> print(a)
[]
>>> print(b)
[]
>>> a is b
True
You could also do:
>>> a[:] = []
这篇关于不同的清单方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文