Python append 與深拷貝 淺拷貝

2022-09-23 00:52:15 字數 1352 閱讀 8653

class

solution:

def combine(self, n: int, k: int) ->list[list[int]]:

res =

path =

defbacktracing(n, start_i):

if len(path) ==k:

return

for i in range(start_i, n+1):

backtracing(n, i+1)

path.pop()

backtracing(n, 1)

return res

>>>alist =

>>> num = [2]

>>> id( num ) ==id( alist[0] )

true

如果希望是深拷貝,則需要寫成:

leetcode77中,因為物件是一維列表,所以淺拷貝就夠了。

另附:直接賦值、淺拷貝、深拷貝:

import

copy

a = [1, 2, 3, 4, ['

a', '

b']] #

原始物件

b = a #

賦值,傳物件的引用

c = copy.copy(a) #

物件拷貝,淺拷貝

d = copy.deepcopy(a) #

物件拷貝,深拷貝

修改物件a

c') #

修改物件a中的['a', 'b']陣列物件

print( '

a =

', a )

print( '

b =

', b )

print( '

c =

', c )

print( '

d =

', d )

執行結果為:

('

a =

', [1, 2, 3, 4, ['

a', '

b', '

c'], 5])('

b =

', [1, 2, 3, 4, ['

a', '

b', '

c'], 5])('

c =

', [1, 2, 3, 4, ['

a', '

b', 'c'

]])(

'd =

', [1, 2, 3, 4, ['

a', '

b']])