赞
踩
实际上,列表中的所有对象都是相同的,因此更改一个也会改变其他对象:In [151]: some_list = 4 * [(4 * [0])] In [152]: [id(x) for x in some_list]Out[152]: [148641452, 148641452, 148641452, 148641452]In [160]: some_list[0][1]=5 #you think you changed the list at index 0 hereIn [161]: some_listOut[161]: [[0, 5, 0, 0], [0, 5, 0, 0], [0, 5, 0, 0], [0, 5, 0, 0]] #but all lists are changed
以如下方式创建列表:In [156]: some_list=[[0]*4 for _ in range(4)]In [157]: some_listOut[157]: [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]In [158]: [id(x) for x in some_list]Out[158]: [148255436, 148695180, 148258380, 148255852]In [163]: some_list[0][1]=5In [164]: some_listOut[164]: [[0, 5, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] #works fine in this case
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。