参考文献:https://blog.youkuaiyun.com/qq_29721419/article/details/70310183
试图在列表中存放字典时出了问题
dict1 = {}
list1 = []
for i in range(10):
dict1['test'] = i
list1.append(dict1)
print(list1)
# Result :
[{'test': 9}, {'test': 9}, {'test': 9}, {'test': 9}, {'test': 9}, {'test': 9}, {'test': 9}, {'test': 9}, {'test': 9}, {'test': 9}]
这显然不是预期所要的结果,在优快云查了一下:在使用append方法将字典添加到列表中时,如果改变字典,列表数据也会随之改变,这是因为dict在Python里是object,不属于primitive type(即int、float、string、None、bool)。这意味着你一般操控的是一个指向object(对象)的指针,而非object本身。下面是改善方法:使用copy()
dict1 = {}
list1 = []
for i in range(10):
dict1['test'] = i
list1.append(dict1.copy())
print(list1)
# Result:
[{'test': 0}, {'test': 1}, {'test': 2}, {'test': 3}, {'test': 4}, {'test': 5}, {'test': 6}, {'test': 7}, {'test': 8}, {'test': 9}]