天天看點

python中在list中添加字典遇到的問題

在寫python時,遇到了如上問題,代碼複現如下

a = []
b = {}
for i in range(2):
    b['num'] = i
    a.append(b)      

本意是想的到

[{‘num’:0},{‘num’:1}] 

但是實際卻是 

[{‘num’:1},{‘num’:1}]

執行id(a[0])和id(a[1])發現這兩者的索引是一樣的, 

這樣就能了解了 

在python中,一切對象,是進行引用傳遞的

解決辦法

介紹一下這個方法屬性copy

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below). 

Interface summary:

  • A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
  • A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.