这两行之间有什么区别:
arr[:] = []
arr = []
我知道他们两个清单。
答案 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]