python3.x中arr [:] = []和arr [] = []之间的区别?

时间:2014-05-03 05:51:58

标签: python list python-3.x

这两行之间有什么区别:

arr[:] = []
arr = []

我知道他们两个清单。

1 个答案:

答案 0 :(得分:1)

对于第二个,我认为你的意思是arr = []

不同之处在于, arr 指向空列表,只是减少现有列表中的引用计数。

只有当其他东西指向原始列表时,区别才是重要的。

>>> orig = [10, 20, 30]
>>> arr = orig              # Second reference to the same list.
>>> arr[:] = []             # Clears the one list, so that arr and orig are empty
>>> orig
[]

与之对比:

>>> orig = [10, 20, 30]
>>> arr = orig              # Second reference to the same list.
>>> arr = []                # Points arr to a new list, leaving orig unchanged
>>> orig
[10, 20, 30]