導航:首頁 > 編程語言 > pythondict深復制

pythondict深復制

發布時間:2022-07-25 15:05:26

python中淺拷貝和深拷貝的區別

python一般有三種拷貝方法。
以alist=[1,2,3,["a","b"]]為例:
(1)直接賦值。傳遞對象的引用而已,原始列表改變,被賦值的b也會做相同的改變
>>> b=alist
>>> print b
[1, 2, 3, ['a', 'b']]
>>> alist.append(5)
>>> print alist;print b
[1, 2, 3, ['a', 'b'], 5]
[1, 2, 3, ['a', 'b'], 5]
(2)淺拷貝。沒有拷貝子對象,所以原始數據改變,子對象會改變。
>>> import
>>> c=.(alist)
>>> print alist;print c
[1, 2, 3, ['a', 'b']]
[1, 2, 3, ['a', 'b']]
>>> alist.append(5)
>>> print alist;print c
[1, 2, 3, ['a', 'b'], 5]
[1, 2, 3, ['a', 'b']]
>>> alist[3]
['a', 'b']
>>> alist[3].append('cccc')
>>> print alist;print c
[1, 2, 3, ['a', 'b', 'cccc'], 5]
[1, 2, 3, ['a', 'b', 'cccc']] 裡面的子對象被改變了
(3)深拷貝。包含對象裡面的自對象的拷貝,所以原始對象的改變不會造成深拷貝里任何子元素的改變。
>>> import
>>> d=.deep(alist)
>>> print alist;print d
[1, 2, 3, ['a', 'b']]
[1, 2, 3, ['a', 'b']]始終沒有改變
>>> alist.append(5)
>>> print alist;print d
[1, 2, 3, ['a', 'b'], 5]
[1, 2, 3, ['a', 'b']]始終沒有改變
>>> alist[3]
['a', 'b']
>>> alist[3].append("ccccc")
>>> print alist;print d
[1, 2, 3, ['a', 'b', 'ccccc'], 5]
[1, 2, 3, ['a', 'b']] 始終沒有改變

② Python裡面如何拷貝一個對象(賦值,淺拷貝,深拷貝的區別)

賦值(=):就是創建了對象的一個新的引用,修改其中任意一個變數都會影響到另一個。
淺拷貝:創建一個新的對象,但它包含的是對原始對象中包含項的引用(如果用引用的方式修改其中一個對象,另外一個也會修改改變){1,完全切片方法;2,工廠函數,如list();3,模塊的()函數}
深拷貝:創建一個新的對象,並且遞歸的復制它所包含的對象(修改其中一個,另外一個不會改變){模塊的deep.deep()函數}

③ python深拷貝和淺拷貝的區別

1、淺拷貝(shallow )

所謂「淺拷貝」,是指創建一個新的對象,其內容是原對象中元素的引用。(拷貝組合對象,不拷貝子對象)

常見的淺拷貝有:切片操作、工廠函數、對象的()方法、模塊中的函數。

2、深拷貝(deep )

所謂「深拷貝」,是指創建一個新的對象,然後遞歸的拷貝原對象所包含的子對象。深拷貝出來的對象與原對象沒有任何關聯。

深拷貝只有一種方式:模塊中的deep函數。

總結:

淺拷貝,沒有拷貝子對象,所以原始數據改變,子對象會改變

深拷貝,包含對象裡面的自對象的拷貝,所以原始對象的改變不會造成深拷貝里任何子元素的改變

④ python3 defaultdict 和 dict的區別

yangyzh
Python中dict詳解

python3.0以上,print函數應為print(),不存在dict.iteritems()這個函數。

在python中寫中文注釋會報錯,這時只要在頭部加上# coding=gbk即可

#字典的添加、刪除、修改操作
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
dict["w"] = "watermelon"
del(dict["a"])
dict["g"] = "grapefruit"
print dict.pop("b")
print dict
dict.clear()
print dict
#字典的遍歷
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for k in dict:
print "dict[%s] =" % k,dict[k]
#字典items()的使用
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
#每個元素是一個key和value組成的元組,以列表的方式輸出
print dict.items()
#調用items()實現字典的遍歷
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
for (k, v) in dict.items():
print "dict[%s] =" % k, v
#調用iteritems()實現字典的遍歷
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
print dict.iteritems()
for k, v in dict.iteritems():
print "dict[%s] =" % k, v
for (k, v) in zip(dict.iterkeys(), dict.itervalues()):
print "dict[%s] =" % k, v

#使用列表、字典作為字典的值
dict = {"a" : ("apple",), "bo" : {"b" : "banana", "o" : "orange"}, "g" : ["grape","grapefruit"]}
print dict["a"]
print dict["a"][0]
print dict["bo"]
print dict["bo"]["o"]
print dict["g"]
print dict["g"][1]

dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
#輸出key的列表
print dict.keys()
#輸出value的列表
print dict.values()
#每個元素是一個key和value組成的元組,以列表的方式輸出
print dict.items()
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
it = dict.iteritems()
print it
#字典中元素的獲取方法
dict = {"a" : "apple", "b" : "banana", "c" : "grape", "d" : "orange"}
print dict
print dict.get("c", "apple")
print dict.get("e", "apple")
#get()的等價語句
D = {"key1" : "value1", "key2" : "value2"}
if "key1" in D:
print D["key1"]
else:
print "None"
#字典的更新
dict = {"a" : "apple", "b" : "banana"}
print dict
dict2 = {"c" : "grape", "d" : "orange"}
dict.update(dict2)
print dict
#udpate()的等價語句
D = {"key1" : "value1", "key2" : "value2"}
E = {"key3" : "value3", "key4" : "value4"}
for k in E:
D[k] = E[k]
print D
#字典E中含有字典D中的key
D = {"key1" : "value1", "key2" : "value2"}
E = {"key2" : "value3", "key4" : "value4"}
for k in E:
D[k] = E[k]
print D
#設置默認值
dict = {}
dict.setdefault("a")
print dict
dict["a"] = "apple"
dict.setdefault("a","default")
print dict
#調用sorted()排序
dict = {"a" : "apple", "b" : "grape", "c" : "orange", "d" : "banana"}
print dict
#按照key排序
print sorted(dict.items(), key=lambda d: d[0])
#按照value排序
print sorted(dict.items(), key=lambda d: d[1])
#字典的淺拷貝
dict = {"a" : "apple", "b" : "grape"}
dict2 = {"c" : "orange", "d" : "banana"}
dict2 = dict.()
print dict2

#字典的深拷貝
import
dict = {"a" : "apple", "b" : {"g" : "grape","o" : "orange"}}
dict2 = .deep(dict)
dict3 = .(dict)
dict2["b"]["g"] = "orange"
print dict
dict3["b"]["g"] = "orange"
print dict

補充:
1 初始化
>>> d = dict(name='visaya', age=20)
>>> d = dict(zip(['name', 'age'], ['visaya', 20]))

#dict.fromkeys(listkeys, default=0) 把listkeys中的元素作為key均賦值為value,默認為0
>>> d = dict.fromkeys(['a', 'b'], 1)
>>> d
{'a': 1, 'b': 1}
2 字典視圖和幾何
dict.keys()類似信使可以進行交集和並集等集合操作(類似集合,因為不存在重復的項),但dict.values()不可以進行如上操作。

>>> k = d.keys()
>>> k
dict_keys(['a', 'b'])
>>> list(k)
['a', 'b']
>>> k | {'x': 3}
{'a', 'x', 'b'}
>>> k | {'x'}
{'a', 'x', 'b'}
>>> k | {'x', 'y'}
{'a', 'y', 'b', 'x'}
>>> k & {'x'}
set()
>>> v = d.values()
>>> v
dict_values([1, 2])
>>> v | {'x'}
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
TypeError: unsupported operand type(s) for |: 'dict_values' and 'set'
3 排序字典鍵
兩種方法:
3.1 sort:
>>> Ks = list(d.keys())
>>> Ks.sort()
>>> for k in Ks:
... print(k, d[k])
...
a 1
b 2
3.2 sorted:
>>> for k in sorted(d.keys()):
... print(k, d[k])
...
a 1
b 2

3.3 注意
>>> for k in list(d.keys()).sort():
... print(k, d[k])
...
Traceback (most recent call last):
File "<stdin>", line 1, in <mole>
TypeError: 'NoneType' object is not iterable

出錯原因:
list.sort() list.append()函數都是對自身的操作,沒有返回值,故需先將list(d.keys())的結果保存下來,在結果上進行sort()
4 常用函數
4.1 get()
D.get(k[, d]) => D[k] if k in D else d. d defaults to none.
4.2 pop()
D.pop(value[, d]) => Remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised.
4.3 udpate()
D.update(E, **F) -> None. Update D from dict/iterable E and F.
If E has a .keys() method, does: for k in E: D[k] = E[k]
If E lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]

>>> d = dict(name='visaya', age=21)
>>> d1= {'age': 20, 'sex': 'male'}
>>> d2 = zip(['a', 'b'], [1, 2])

>>> d.update(d1)
>>> d
{'age': 20, 'name': 'visaya', 'sex': 'male'}
#for k in d1: d[k] = d1[k]

>>> d.update(d2)
>>> d
{'age': 20, 'name': 'visaya', 'sex': 'male'}
#for (k, v) in d2: d[k] = v
4.4 del()
del D[key]
4.5 clear()
4.6 ()
Python中的dict
初始化
構造方法創建
Python代碼
d = dict()
d = dict(name="nico", age=23)
d = dict((['name', "nico"], ['age', 23]))
當然還有更方便,簡單的
Python代碼
d = {}
d = {"name":"nico", "age":23}

遍歷
通過對key的遍歷,遍歷整個dict

Python代碼
d = {"name":"nico", "age":23}
for key in d:
print "key=%s, value=%s" % (key, d[key])

for key in d.iterkeys():
print "key=%s, value=%s" % (key, d[key])

for key in d.keys():
print "key=%s, value=%s" % (key, d[key])

for key in iter(d):
print "key=%s, value=%s" % (key, d[key])

for key,item in d.items():
print "key=%s, value=%s" % (key, item)

當然也可以直接遍歷value

Python代碼
d = {"name":"nico", "age":23}
for value in d.values():
print value

for key,value in d.viewitems():
print "key=%s, value=%s" % (key, value)

for value in d.viewvalues():
print "value=%s" % (value)
這里values和viewvalues的區別

後者返回的是該字典的一個view對象,類似資料庫中的view,當dict改變時,該view對象也跟著改變

常用方法

Python代碼
d = {"name":"nico", "age":23}
d["name"] = "aaaa"
d["address"] = "abcdefg...."
print d #{'age': 23, 'name': 'aaaa', 'address': 'abcdefg....'}

獲取dict值
Python代碼
print d["name"] #nico
print d.get("name") #nico

如果key不在dict中,返回default,沒有為None
Python代碼
print d.get("namex", "aaa") #aaa
print d.get("namex") #None

排序sorted()
Python代碼
d = {"name":"nico", "age":23}
for key in sorted(d):
print "key=%s, value=%s" % (key, d[key])
#key=age, value=23
#key=name, value=nico

刪除del
Python代碼
d = {"name":"nico", "age":23}
Python代碼
del d["name"]
#如果key不在dict中,拋出KeyError
del d["names"]
Python代碼
Traceback (most recent call last):
File "F:\workspace\project\pydev\src\ddd\ddddd.py", line 64, in <mole>
del d["names"]
KeyError: 'names'

清空clear()
Python代碼
d = {"name":"nico", "age":23}
d.clear()
print d #{}

()
Python代碼
d1 = d.() #{'age': 23, 'name': 'nico'}
#使用返回view對象
d2 = d1.viewitems() #dict_items([('age', 23), ('name', 'nico')])
#修改字典d1,新增元素
d1["cc"] = "aaaaaa"
print d2
#dict_items([('cc', 'aaaaaa'), ('age', 23), ('name', 'nico')])

pop(key[, default])
如果key在dict中,返回,不在返回default
Python代碼
#如果key在dict中,返回,不在返回default
print d.pop("name", "niccco") #nico
print d.pop("namezzz", "niccco") #niccco
#key不在dict中,且default值也沒有,拋出KeyError
print d.pop("namezzz") #此處拋出KeyError

popitem()
刪除並返回dict中任意的一個(key,value)隊,如果字典為空會拋出KeyError
Python代碼
d = {"name":"nico", "age":23}
print d.popitem() #('age', 23)
print d.popitem() #('name', 'nico')
#此時字典d已為空
print d.popitem() #此處會拋出KeyError

update([other])
將字典other中的元素加到dict中,key重復時將用other中的值覆蓋
Python代碼
d = {"name":"nico", "age":23}
d2 = {"name":"jack", "abcd":123}
d.update(d2)
print d #{'abcd': 123, 'age': 23, 'name': 'jack'}

⑤ python dict淺復制

yangyzh

Python中dict詳解
python3.0以上,print函數應為print(),不存在dict.iteritems()這個函數。
在python中寫中文注釋會報錯,這時只要在頭部加上# coding=gbk即可
#字典的添加、刪除、修改操作
dict = {"a" : "apple", "b" : "banana", "g" : "grape", "o" : "orange"}
dict["w"] = "watermelon"
del(dict["a"])
dict["g"] = "grapefruit"
print dict.pop("b")
print dict
dict.clear()
print dict

⑥ Python的復制,深拷貝和淺拷貝的區別

簡單點說
1. . 淺拷貝 只拷貝父對象,不會拷貝對象的內部的子對象。
2. .deep 深拷貝 拷貝對象及其子對象
用一個簡單的例子說明如下:
>>>import
>>>a = [1, 2, 3, 4, ['a', 'b', 'c']]
>>> b = a
>>> c = .(a)
>>> d = .deep(a)
很容易理解:a是一個列表,表內元素a[4]也是一個列表(也就是一個內部子對象);b是對a列表的又一個引用,所以a、b是完全相同的,可以通過id(a)==id(b)證明。
第4行是淺拷貝,第五行是深拷貝,通過id(c)和id(d)可以發現他們不相同,且與id(a)都不相同:
>>> id(a)
19276104
>>> id(b)
19276104
>>> id(c)
19113304
>>> id(d)
19286976
至於如何看深/淺拷貝的區別,可以通過下面的操作來展現:
>>> a.append(5) #操作1
>>> a[4].append('hello') #操作2
這時再查看結果:
>>> a
[1, 2, 0, 4, ['a', 'b', 'c', 'hello'], 5]
>>> b
[1, 2, 0, 4, ['a', 'b', 'c', 'hello'], 5]
>>> c
[1, 2, 3, 4, ['a', 'b', 'c', 'hello']]
>>> d
[1, 2, 3, 4, ['a', 'b', 'c']]
可以發現a、b受了操作1、2的影響,c只受操作2影響,d不受影響。a、b結果相同很好理解。由於c是a的淺拷貝,只拷貝了父對象,因此a的子對象( ['a', 'b', 'c', 'hello'])改變時會影響到c;d是深拷貝,完全不受a的影響

⑦ Python的列表有沒有淺復制跟深復制的概念

有的。比如:

首先這里導入模塊,並生成三個列表

發現list2和list3有不同,其中list2就是淺復制,list3就是深復制

淺復制就是指當對象的欄位值被復制時,欄位引用的對象不會被復制,也就是引用的對象和原數據還是同一個,並沒有產生一個新的對象

深復制指對對象中欄位引用的對象也進行復制的一種方式,會產生一個新的值相同的不同對象

⑧ Python中的dict怎麼用

#字典的添加、刪除、修改操作
dict={"a":"apple","b":"banana","g":"grape","o":"orange"}
dict["w"]="watermelon"
del(dict["a"])
dict["g"]="grapefruit"
printdict.pop("b")
printdict
dict.clear()
printdict
#字典的遍歷
dict={"a":"apple","b":"banana","g":"grape","o":"orange"}
forkindict:
print"dict[%s]="%k,dict[k]
#字典items()的使用
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
#每個元素是一個key和value組成的元組,以列表的方式輸出
printdict.items()
#調用items()實現字典的遍歷
dict={"a":"apple","b":"banana","g":"grape","o":"orange"}
for(k,v)indict.items():
print"dict[%s]="%k,v
#調用iteritems()實現字典的遍歷
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
printdict.iteritems()
fork,vindict.iteritems():
print"dict[%s]="%k,v
for(k,v)inzip(dict.iterkeys(),dict.itervalues()):
print"dict[%s]="%k,v


#使用列表、字典作為字典的值
dict={"a":("apple",),"bo":{"b":"banana","o":"orange"},"g":["grape","grapefruit"]}
printdict["a"]
printdict["a"][0]
printdict["bo"]
printdict["bo"]["o"]
printdict["g"]
printdict["g"][1]

dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
#輸出key的列表
printdict.keys()
#輸出value的列表
printdict.values()
#每個元素是一個key和value組成的元組,以列表的方式輸出
printdict.items()
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
it=dict.iteritems()
printit
#字典中元素的獲取方法
dict={"a":"apple","b":"banana","c":"grape","d":"orange"}
printdict
printdict.get("c","apple")
printdict.get("e","apple")
#get()的等價語句
D={"key1":"value1","key2":"value2"}
if"key1"inD:
printD["key1"]
else:
print"None"
#字典的更新
dict={"a":"apple","b":"banana"}
printdict
dict2={"c":"grape","d":"orange"}
dict.update(dict2)
printdict
#udpate()的等價語句
D={"key1":"value1","key2":"value2"}
E={"key3":"value3","key4":"value4"}
forkinE:
D[k]=E[k]
printD
#字典E中含有字典D中的key
D={"key1":"value1","key2":"value2"}
E={"key2":"value3","key4":"value4"}
forkinE:
D[k]=E[k]
printD
#設置默認值
dict={}
dict.setdefault("a")
printdict
dict["a"]="apple"
dict.setdefault("a","default")
printdict
#調用sorted()排序
dict={"a":"apple","b":"grape","c":"orange","d":"banana"}
printdict
#按照key排序
printsorted(dict.items(),key=lambdad:d[0])
#按照value排序
printsorted(dict.items(),key=lambdad:d[1])
#字典的淺拷貝
dict={"a":"apple","b":"grape"}
dict2={"c":"orange","d":"banana"}
dict2=dict.()
printdict2

#字典的深拷貝
import
dict={"a":"apple","b":{"g":"grape","o":"orange"}}
dict2=.deep(dict)
dict3=.(dict)
dict2["b"]["g"]="orange"
printdict
dict3["b"]["g"]="orange"
printdict

⑨ python的復制,深拷貝和淺拷貝的區別

在Python中存在深拷貝與淺拷貝的區別,相信有些Python初學者可能就有些疑惑,是指什麼意思呢?
1. 賦值其實只是傳遞對象引用,引用對象id是一樣的。
2. 淺拷貝是指拷貝的只是原始對象元素的引用,換句話說,淺拷貝產生的對象本身是新的,但是它的內容不是新的,只是對原對象的一個引用。
3. 深拷貝是指完全拷貝原始對象,而且產生的對象是新的,並且不受其他引用對象的操作影響。

閱讀全文

與pythondict深復制相關的資料

熱點內容
網站源碼使用視頻 瀏覽:746
stc89c52單片機最小系統 瀏覽:452
郵件安全證書加密 瀏覽:416
雲伺服器如何訪問百度 瀏覽:279
常州電信伺服器dns地址 瀏覽:839
用小方塊製作解壓方塊 瀏覽:42
圖像壓縮編碼實現 瀏覽:68
特色功能高拋低吸線副圖指標源碼 瀏覽:71
西方哲學史pdf羅素 瀏覽:874
python最常用模塊 瀏覽:184
溫州直播系統源碼 瀏覽:112
程序員在上海買房 瀏覽:384
生活解壓游戲機 瀏覽:909
季羨林pdf 瀏覽:718
php支付寶介面下載 瀏覽:816
ipad怎麼把app資源庫關了 瀏覽:301
量柱比前一天多源碼 瀏覽:416
電子書app怎麼上傳 瀏覽:66
國家反詐中心app注冊怎麼開啟 瀏覽:804
全波差分傅里葉演算法窗長 瀏覽:41