列表是可變對象的問題,所以ll=l=[]
意味着ll
是 完全相同對象爲l
。這可以通過使用is
操作進行驗證:
>>> ll is l
True
這可以證明如下:
>>> a=b=[]
>>> a
[]
>>> b
[]
>>> a.append(1)
>>> a
[1]
>>> b # For all practical purposes, a is identical to b
[1]
>>> a is b
True
因此,線ll.append(l)
創建一個遞歸的對象! 使用pprint
模塊運行上述代碼狀態這顯然後:
>>> # Run the posted code
>>> import pprint
>>> pprint.pprint(ll)
[[1, 2, 3, 4],
<Recursion on list with id=2032187430600>,
[5, 6, 7, 8],
<Recursion on list with id=2032187430600>,
[9, 10, 11, 12],
<Recursion on list with id=2032187430600>]
的ll
列表實際上不是必須的,因爲l.append
方法已經 追加新生成的列表發送給l
對象並創建一個二維列表:
>>> q=[[1,2,3,4]]
>>> q.append([5,6,7,8])
>>> q
[[1, 2, 3, 4], [5, 6, 7, 8]]
的代碼可以被重寫如下:
a = [1,2,3,4,5,6,7,8,9,10,11,12]
l = list()
f,k = 0,4
# range(1,4) iterates m through the values [1, 2, 3]
# This includes the first but excludes the last
for m in range(1,4):
# f and k are already integers, so no need for typecasting
# This append statement will append the 1D slice as a single unit
l.append(a[f:k])
# a += 1 is the same as a = a + 1 but is more compact
f += 4
k += 4
print(l)
# Will be [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
如果您確實需要創建兩個單獨的空列表,最好這樣做:
>>> q=list()
>>> w=list()
>>> q is w
False