假设我具有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]]
我不知道为什么,是什么让它做到这一点?
另见http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-大小均匀的蟒蛇 – matsjoyce 2014-10-29 17:35:59
原因:[列表的Python列表,更改反映在子列表意外](http://stackoverflow.com/questions/240178/unexpected-feature-in-a-python-list-of -lists) – 2014-10-29 17:36:43
哦,哇,从来没有想过这个!谢谢指出, – jean 2014-10-29 17:37:56