2014-10-29 48 views
0

假設我具有9項, 一個的列表我想通過3項轉換1-d列表到2-d列表在Python

從[1,2將其轉化成的3列表,3,4,5,6,7,8,9] - > [[1,2,3],[4,5,6],[7,8,9]]

這是代碼:

def main(): 

    L = range(1,10) 
    twoD= [[0]*3]*3  #creates [[0,0,0],[0,0,0],[0,0,0]] 

    c = 0 
    for i in range(3): 
     for j in range(3): 
      twoD[i][j] = L[c] 

      c+=1 

由於某種原因,這個返回

twoD = [[7, 8, 9], [7, 8, 9], [7, 8, 9]] 

我不知道爲什麼,是什麼讓它做到這一點?

+0

另見http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-大小均勻的蟒蛇 – matsjoyce 2014-10-29 17:35:59

+0

原因:[列表的Python列表,更改反映在子列表意外](http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of -lists) – 2014-10-29 17:36:43

+0

哦,哇,從來沒有想過這個!謝謝指出, – jean 2014-10-29 17:37:56

回答

0

您可以使用以下列表理解。

>>> l = [1,2,3,4,5,6,7,8,9] 
>>> [l[i:i+3] for i in range(0, len(l), 3)] 
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 

更一般地,你可以寫這樣的功能

def reshape(l, d): 
    return [l[i:i+d] for i in range(0, len(l), d)] 


>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] 

>>> reshape(l,3) 
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]] 

>>> reshape(l,5) 
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]] 
+1

這是一個偉大的技術,但我想明白爲什麼我的返回錯誤的價值? – jean 2014-10-29 17:36:39

+0

因爲您生成內部列表的方式是複製相同的子列表。請在評論中查看上述鏈接的帖子。 – CoryKramer 2014-10-29 17:39:27