2012-04-14 95 views

回答

25
a_list = ['foo', 'bar'] 

在內存中創建一個新的list和它指向的名字a_list。這與a_list之前指出的無關。

a_list[:] = ['foo', 'bar'] 

調用a_list對象與slice作爲索引,並在存儲器中作爲值創建了新的list方法__setitem__

__setitem__評估slice以找出它所代表的索引,並在其傳遞的值上調用iter。然後它遍歷該對象,將slice指定的範圍內的每個索引設置爲該對象的下一個值。對於list s,如果由slice指定的範圍與可迭代的長度不同,則調整list的大小。這允許你做一些有趣的東西,如一個列表刪除部分:

a_list[:] = [] # deletes all the items in the list, equivalent to 'del a_list[:]' 

或列表中的中間插入新的價值觀:

a_list[1:1] = [1, 2, 3] # inserts the new values at index 1 in the list 

然而,隨着「擴展切片」 ,其中step不是一個,可迭代必須是正確的長度:

>>> lst = [1, 2, 3] 
>>> lst[::2] = [] 
Traceback (most recent call last): 
    File "<interactive input>", line 1, in <module> 
ValueError: attempt to assign sequence of size 0 to extended slice of size 2 

是約切片分配給不同a_list的主要事情是:

  1. a_list必須已經指向
  2. 該對象被修改,而不是在一個新的對象指向a_list,對象
  3. 該對象必須支持__setitem__slice指數
  4. 右邊的對象必須支持迭代
  5. 沒有名稱指向右側的對象。如果沒有其他引用(例如,當它是一個字面值時),那麼在迭代完成後它將被引用計數不存在。
+0

我特別喜歡編輯的部分:) – 0xc0de 2012-04-14 18:28:37

+0

我在文檔(http://docs.python.org/tutorial/introduction.html#lists)中閱讀了這個內容。只是默認的索引是我的懷疑:) – 0xc0de 2012-04-14 19:00:27

+1

「對於列表,如果切片指定的範圍與可迭代的長度不同,則列表將調整大小。」只有當範圍的步長值爲1時纔是如此。對於除1以外的步長值,分配的迭代必須產生正確數量的項目。 – 2012-04-15 16:57:31

12

區別相當大!在

a_list[:] = ['foo', 'bar'] 

您修改了一個綁定到名稱a_list的現有列表。另一方面,

a_list = ['foo', 'bar'] 

給名稱a_list分配一個新列表。

也許這將幫助:

a = a_list = ['foo', 'bar'] # another name for the same list 
a_list = ['x', 'y'] # reassigns the name a_list 
print a # still the original list 

a = a_list = ['foo', 'bar'] 
a_list[:] = ['x', 'y'] # changes the existing list bound to a 
print a # a changed too since you changed the object 
2

通過分配到a_list[:]a_list仍然參考同一個列表對象,與修改的內容。通過分配a_list,a_list現在引用新的列表對象。

退房其id

>>> a_list = [] 
>>> id(a_list) 
32092040 
>>> a_list[:] = ['foo', 'bar'] 
>>> id(a_list) 
32092040 
>>> a_list = ['foo', 'bar'] 
>>> id(a_list) 
35465096 

正如你可以看到,它的id與切片分配版本好好嘗試一下改變。


兩者之間的不同可能會導致完全不同的結果,例如,當列表的功能參數:

def foo(a_list): 
    a_list[:] = ['foo', 'bar'] 

a = ['original'] 
foo(a) 
print(a) 

有了這個,a被修改爲好,但如果a_list = ['foo', 'bar']是相反,a保持其原始價值。

相關問題