解决python字典对值(值为列表)赋值出现重复的问题
可能很少有人遇到这个问题,网上也没找到,这里记录一下,希望也可以帮到其他人。
问题描述:假设有一个字典data,其键不定,可能随时添加键(这不是关键),某一个键下面对应的值为一个长度为10的list,初始化为0,然后我想修改某些键下面的列表中的某一个值,比如data有一个键'k',对应的值为[0,0,0,0,0,0,0,0,0,0],现在我想把键'k'对应的列表的第三个数改成3,即[0,0,3,0,0,0,0,0,0,0],可是意外的事情发生了,如果data还有一个键'k1',假设其值为[0,0,0,0,0,0,0,0,0,0],但是我操作完之后,居然也跟着变成了[0,0,3,0,0,0,0,0,0,0]。
具体代码如下:
data = {} indexes = ['new','repeat'] ret = [{'i':1,'new':3,'repeat':11},{'i':3,'new':2,'repeat':6}, {'i':4,'new':9,'repeat':2},{'i':9,'new':1,'repeat':8}] y_axis = [0]*10 for e in ret: for index in indexes: if not data.has_key(index): data[index] = y_axis i = e['i'] for index in indexes: data[index][i] = e[index] print data
代码不难看懂,我感觉理论上应该输出:{'new': [0, 3, 0, 2, 9, 0, 0, 0, 0, 1], 'repeat': [0, 11, 0, 6, 2, 0, 0, 0, 0, 8]},但是事与愿违,输出是:{'new': [0, 11, 0, 6, 2, 0, 0, 0, 0, 8], 'repeat': [0, 11, 0, 6, 2, 0, 0, 0, 0, 8]},感觉莫名其妙,于是准备调试,先import pdb,再在需要打断点的前一句加pdb.set_trace()即可,如下:
import pdb data = {} indexes = ['new','repeat'] ret = [{'i':1,'new':3,'repeat':11},{'i':3,'new':2,'repeat':6}, {'i':4,'new':9,'repeat':2},{'i':9,'new':1,'repeat':8}] y_axis = [0]*10 for e in ret: for index in indexes: if not data.has_key(index): data[index] = y_axis i = e['i'] for index in indexes: pdb.set_trace() data[index][i] = e[index] print data
接着,python test.py,到赋值data的键对应的列表某一个值那一句:
查看data和index值:
正常。往下执行一步,即执行赋值操作,再查看data值:
在这里真想来一句mdblgl,明明index是'new',明明是对data['new'][1]赋值,关data['repeat'][1]屁事,它跟着变什么?可想而知,后面对data['repeat'][1]再赋一个值11,那'new'的值不就也跟着一起变,结果就是得到了最后那个莫名其妙的结果。
试过很多办法,想过很多原因,无赖才疏学浅,不知道是什么原理,最后,只好用一种非常笨的方法解决了:
data = {} indexes = ['new','repeat'] ret = [{'i':1,'new':3,'repeat':11},{'i':3,'new':2,'repeat':6}, {'i':4,'new':9,'repeat':2},{'i':9,'new':1,'repeat':8}] y_axis = [0]*10 tmp = y_axis*len(indexes) for k in range(len(indexes)): for e in ret: i = e['i'] tmp[i+len(y_axis)*k] = e[indexes[k]] for k in range(len(indexes)): data[indexes[k]] = tmp[(k*len(y_axis)):((k+1)*len(y_axis))] print data
在此,希望知道为什么这样的大佬指点一下,万分感谢!
以上这篇解决python字典对值(值为列表)赋值出现重复的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。