在這篇文章的指導下,我創建了 4 組不同的字典:Python variables as keys to dict。我現在想將所有這些字典合并到 1 個串列中。我嘗試了以下方法:
classes = ['apple', 'orange', 'pear', 'mango']
class_dict = {}
store = []
for fruit in classes:
if fruit == "orange":
o = 2
q = 1
else:
o = 0
q = 0
for j in ('fruit', 'o', 'q'):
class_dict[j] = locals()[j]
print (class_dict)
store.append(class_dict)
print ("store: ", store)
輸出如下圖所示。如您所見,store僅包含每次附加到它的同一字典的串列。我不確定我要去哪里錯了,對此提供一些幫助將不勝感激!
{'fruit': 'apple', 'o': 0, 'q': 0}
{'fruit': 'orange', 'o': 2, 'q': 1}
{'fruit': 'pear', 'o': 0, 'q': 0}
{'fruit': 'mango', 'o': 0, 'q': 0}
store: [{'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}]
uj5u.com熱心網友回復:
您需要class_dict在回圈內部移動。
classes = ['apple', 'orange', 'pear', 'mango']
store = []
for fruit in classes:
class_dict = {}
if fruit == "orange":
o = 2
q = 1
else:
o = 0
q = 0
for j in ('fruit', 'o', 'q'):
class_dict[j] = locals()[j]
print (class_dict)
store.append(class_dict)
print ("store: ", store)
輸出:
{'fruit': 'apple', 'o': 0, 'q': 0}
{'fruit': 'orange', 'o': 2, 'q': 1}
{'fruit': 'pear', 'o': 0, 'q': 0}
{'fruit': 'mango', 'o': 0, 'q': 0}
store: [{'fruit': 'apple', 'o': 0, 'q': 0}, {'fruit': 'orange', 'o': 2, 'q': 1}, {'fruit': 'pear', 'o': 0, 'q': 0}, {'fruit': 'mango', 'o': 0, 'q': 0}]
uj5u.com熱心網友回復:
您應該class_dict在回圈內移動:
classes = ['apple', 'orange', 'pear', 'mango']
store = []
for fruit in classes:
class_dict = {}
if fruit == "orange":
o = 2
q = 1
else:
o = 0
q = 0
for j in ('fruit', 'o', 'q'):
class_dict[j] = locals()[j]
print (class_dict)
store.append(class_dict)
print ("store: ", store)
這是因為它dict是 python 中的可變物件,并且在回圈的每次迭代中,您for都會更改全域變數的值class_dict。它的簡單示例:
>>> a = {'a': 1, 'b': 2}
>>> a
{'a': 1, 'b': 2}
>>> b = a
>>> b
{'a': 1, 'b': 2}
>>> b['c'] = 3
>>> b
{'a': 1, 'b': 2, 'c': 3}
>>> a
{'a': 1, 'b': 2, 'c': 3}
當您class_dict在回圈內部移動時,此變數變為區域變數,并且回圈的迭代變得獨立。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410027.html
標籤:
上一篇:Python嵌套字典訪問問題
下一篇:串列中的嵌套字典
