pyhton 的copy與賦值

2021-08-16 19:38:38 字數 1765 閱讀 2485

今天在做爬蟲的時候,為了防止在填寫字典key的時候,提前定義好了需要資料的字典格式,

在開發過程中遇到了資料結果全部相同的問題,在排查後終於發現問題所在,決定把這個小經驗寫下來。

直接上例子**:

a = 

defgetres

(reslist):

t = a

res =

for each in reslist:

t['a'] = each[0]

t['b'] = each[1]

t['c'] = each[2]

print

't--',t

return res

reslist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

res = getres(reslist)

print

'res---', res

執行結果為:

t-- 

t--

t--

res--- [, , ]

從中發現雖然列印的時候t的值不同,但是在重新執行getres函式時候,由於字典內容的修改,導致列表中的物件內容也跟著修改了。

然後查詢問題,對t重新進行複製,並列印id

def

getres

(reslist):

t = a

res =

for each in reslist:

t['a'] = each[0]

t['b'] = each[1]

t['c'] = each[2]

d = t

print

'd--',id(d)

print

't---',id(t)

return res

輸出結果發現他們在記憶體中的位址是一樣,賦值 = 為# 淺拷貝: 只是引用物件,他們在記憶體中的位址是一樣,d的值會隨著t的改變而改變

d-- 41604056

t--- 41604056

d-- 41604056

t--- 41604056

d-- 41604056

t--- 41604056

res--- [, , ]

於是嘗試使用字典的copy方法。copy函式也是淺拷貝:深拷貝父物件(一級目錄),子物件(二級目錄)不拷貝,還是引用

def

getres

(reslist):

t = a

res =

for each in reslist:

t['a'] = each[0]

t['b'] = each[1]

t['c'] = each[2]

d = t.copy()

print

'd--',id(d)

print

't---',id(t)

return res

輸出結果為

d-- 44751512

t--- 44750072

d-- 44751224

t--- 44750072

d-- 44754680

t--- 44750072

res--- [, , ]

這裡d copy t後的記憶體位址發生了改變,列表中的d不會隨著t的改變而改變。

賦值運算與深淺copy

1 複製運算 l1 1,2,3,a b l2 l1 l1 0 111 print l1 111,2,3,a b print l2 111,2,3,a b l1 3 0 hello print l1 111,2,3,hello b print l2 111,2,3,hello b 所以,對於賦值運算來...

簡單了解Python字典copy與賦值的區別

描述 python 字典 dictionary copy 函式返回乙個字典的淺複製。語法copy 方法語法 dict.copy 返回值返回乙個字典的淺複製。例項以下例項展示了 copy 函式的使用方法 dict1 dict2 dict1.copy print new dictinary s str ...

Python列表賦值 淺copy 深copy的區別

1.python中列表的賦值操作 賦值操作在其他語言裡也很常見,例 name1 centos 123123,fedora freebsd uos deepin flag name2 name1 這是python中列表的賦值方式,經過列印後列表name2和列表name1是一樣的 centos 1231...