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

     在此,希望知道爲什麼這樣的大佬指點一下,萬分感謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章