關於深拷貝和淺拷貝的筆試題
阿新 • • 發佈:2018-11-02
-
思考下面的程式碼執行出的結果是什麼:
list = [0, 1, 2]
list[1] = list
print(list)
[0,[…],2] -
第1題中如何最終得出list = [0, [0, 1, 2], 2]這樣的結果?
list[1] = [0,1,2] -
經過以下步驟, a和b分別是多少? 為什麼?
a = [0, [1, 2], 3]
b = a[:]
a[0] = 8
a[1][1] = 9
[8,[1,9],3]
[0,[1,9],3]
python裡一切都是指向,這樣來理解會容易很多
[:]是淺拷貝,只拷貝最上面一層 -
如何保證第3題中最終b = [0, [1, 2], 3]
b = copy.deepcopy(a) -
寫出下面程式碼執行結果:
L = [1, 2]
M = L
L = L + [3, 4]
print(L)
print(M)
[1,2,3,4] [1,2] -
寫出下面程式碼執行結果:de
L = [1, 2]
M = L
L += [3, 4]
print(L)
print(M)
[1,2,3,4] [1,2,3,4] -
執行以下程式碼,解釋執行結果:
def foo(a, b, c=[]):
c.append(a)
c.append(b)
print©
foo(1, 2)
foo(1, 2, [])
foo(3, 4)
[1,2] [1,2] [1,2,3,4]