我不明白Python的2.7.12的這種行爲......爲什麼列表中變量的值在Python中更改?
請驗證代碼,粘貼下面:
test = [(('AAA_1', 'BBB_1', 'CCC_1'), 1), (('AAA_2', 'BBB_2', 'CCC_2'), 2),(('AAA_3', 'BBB_3', 'CCC_3'), 3), (('AAA_4', 'BBB_4', 'CCC_4'), 4)]
for i, j in enumerate(test):
for k, l in enumerate(j[0]):
if k == 0:
dc['first'] = l
elif k == 1:
dc['second'] = l
elif k == 2:
dc['third'] = l
elif k == 3:
dc['fourth'] = l
c.append(dc)
print "/n"
print "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXx"
print dc
print json.dumps(c, indent=1)
print c
print json.dumps(c, indent=1)
上面顯示的代碼的結果存儲在公共引擎收錄:http://pastebin.com/GkrTyseg
對我來說什麼是奇怪的: 通過附加列表:c我想收到詞典列表。這些字典可能代表每種類型的AAA,BBB,CCC元組。我使用字典將其轉換爲json,以便通過webservices使用這些數據。
無論如何,我預計接收JSON:
{
"second": "BBB_1",
"third": "CCC_1",
"first": "AAA_1"
},
{
"second": "BBB_2",
"third": "CCC_2",
"first": "AAA_2"
},
{
"second": "BBB_3",
"third": "CCC_3",
"first": "AAA_3"
},
{
"second": "BBB_4",
"third": "CCC_4",
"first": "AAA_4"
}
但實際結果是:
{
"second": "BBB_4",
"third": "CCC_4",
"first": "AAA_4"
},
{
"second": "BBB_4",
"third": "CCC_4",
"first": "AAA_4"
},
{
"second": "BBB_4",
"third": "CCC_4",
"first": "AAA_4"
},
{
"second": "BBB_4",
"third": "CCC_4",
"first": "AAA_4"
}
爲什麼以前附加價值改變他們的價值觀,以新的?
當我使用而不是列表時,我收到了相同的結果:c使用附加字典來獲得漂亮的json,而不是使用list。但結果都是一樣...... 我嘗試使用(而不是名單:C):
main_dc[i+1] = dc
如何防止不更改列表或字典的元素的值?
'dc'從哪裏來?你不斷更新不同值的同一個字典......隨着時間的推移覆蓋舊的字典。我認爲你需要在外循環的每次迭代中創建一個新的'dc'字典。 – tdelaney