2014-10-29 51 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