python-拷貝

1.普通的賦值操做

def print_id(array):
    ids = []
    for ar in array:
        ids.append(id(ar))
    print (array, ids)
    
a = [1, 'abc', [1, 2, 3]]
b = a
b[0] = 'a'
b[1] = 0
b[2] = [1, 3]
print_id(a)
print_id(b)

output:app

(['a', 0, [1, 3]], [4399687320, 140283452869952, 4400308664])
(['a', 0, [1, 3]], [4399687320, 140283452869952, 4400308664])

b = a操做將a對象的地址賦值給b,兩個對象的地址相同code

2.淺拷貝 copy.copy()

a = [1, 'abc', [1, 2, 3]]
copy_a = copy.copy(a)
copy_a[0] = 'a'
copy_a[1] = 0
copy_a[2] = [1, 3]
print_id(a)
print_id(copy_a)

output:對象

[1, 'abc', [1, 2, 3]]
['a', 0, [1, 3]]

copy_a = copy.copy(a) 僅僅是把int,float,str類型的數據進行拷貝,從新開闢地址,對於內層的list,dict直接把原有的地址給新的對象float

相關文章
相關標籤/搜索