我在很多地方都看到使用list
s的片分配。我能夠用(非默認)指數使用時要了解其使用,但我無法理解它像使用:切片整個列表和直接分配的切片分配之間有什麼區別?
a_list[:] = ['foo', 'bar']
是如何從
a_list = ['foo', 'bar']
不同?
我在很多地方都看到使用list
s的片分配。我能夠用(非默認)指數使用時要了解其使用,但我無法理解它像使用:切片整個列表和直接分配的切片分配之間有什麼區別?
a_list[:] = ['foo', 'bar']
是如何從
a_list = ['foo', 'bar']
不同?
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
的主要事情是:
a_list
必須已經指向a_list
,對象__setitem__
有slice
指數區別相當大!在
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
通過分配到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
保持其原始價值。
我特別喜歡編輯的部分:) – 0xc0de 2012-04-14 18:28:37
我在文檔(http://docs.python.org/tutorial/introduction.html#lists)中閱讀了這個內容。只是默認的索引是我的懷疑:) – 0xc0de 2012-04-14 19:00:27
「對於列表,如果切片指定的範圍與可迭代的長度不同,則列表將調整大小。」只有當範圍的步長值爲1時纔是如此。對於除1以外的步長值,分配的迭代必須產生正確數量的項目。 – 2012-04-15 16:57:31