2016-10-10 21 views
0

我希望把「a」到嵌套列表: ,所以我設計了一個while循環:東西蟒蛇意外時,我設計了一個嵌套列表

a = [1,2,3,4,5,6,7,8,9,10,11,12] 
ll = l = [] 
m,f,k = 1,0,4 

while m <= 3: 

    l.append(a[int(f):int(k)]) 
    f = f + 4 
    k = k + 4 

    ll.append(l) 
    m = m+1 

print(ll) 

我想[[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]而不是[[1, 2, 3, 4], [...], [5, 6, 7, 8], [...], [9, 10, 11, 12], [...]]

爲什麼結果包含[...] 哪裏是在while循環

回答

2

列表是可變對象的問題,所以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