欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python列表的淺拷貝與深拷貝

 更新時(shí)間:2022年03月08日 08:43:15   作者:#苦行僧  
這篇文章主要介紹了Python列表的淺拷貝與深拷貝,對(duì)列表深拷貝就是無論怎樣改動(dòng)新列表,單維or多維,原列表都不變,需要的小伙伴可以參考下面更詳細(xì)內(nèi)容

對(duì)列表深拷貝就是無論怎樣改動(dòng)新列表(單維or多維),原列表都不變。

而下面的淺拷貝,對(duì)于多維列表,只是第一維深拷貝了(嵌套的List保存的是地址,復(fù)制過去的時(shí)候是把地址復(fù)制過去了),所以說其內(nèi)層的list元素改變了,原列表也會(huì)變。

一、淺拷貝(均是只對(duì)第一層進(jìn)行深拷貝)

1. for循環(huán)依次賦值

old = [1, [1, 2, 3], 3]
new = []
for i in range(len(old)):
? ? new.append(old[i])
new[0] = 3
new[1][0] = 3
print(old)
print(new)

'''
[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]
'''

2. 使用copy()函數(shù)

old = [1,[1,2,3],3]
new = old.copy()
new[0] = 3
new[1][0] =3
print(old)
print(new)

輸出:

[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]

3. 使用列表生成式

old = [1,[1,2,3],3]
new = [i for i in old]
?
new[0] = 3
new[1][0] = 3
print(old)
print(new)

輸出:

[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]

4. 使用索引 [:]

old = [1,[1,2,3],3]
new = old[:]
?
new[0] = 3
new[1][0] = 3
print(old)
print(new)

輸出:

[1, [3, 2, 3], 3]
[3, [3, 2, 3], 3]

淺拷貝對(duì)于單層列表就是深拷貝,如:

old = [1,2,3]
new = old[:]
new[0] = 666
print(old)
print(new)
"""
[1, 2, 3]
[666, 2, 3]
"""

二、深拷貝

使用用deepcopy()方法,才是真正的復(fù)制了一個(gè)全新的和原列表無關(guān)的:

import copy
old = [1,[1,2,3],3]
new = copy.deepcopy(old)
?
new[0] = 3
new[1][0] = 3
"""
[1, [1, 2, 3], 3]
[3, [3, 2, 3], 3]
"""

到此這篇關(guān)于Python列表的淺拷貝與深拷貝的文章就介紹到這了,更多相關(guān)Python淺拷貝與深拷貝內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論