溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

對(duì)python append 與淺拷貝的實(shí)例講解

發(fā)布時(shí)間:2020-09-03 05:24:50 來源:腳本之家 閱讀:119 作者:shawpan 欄目:開發(fā)技術(shù)

在做Leetcode的第39題的時(shí)候,看到網(wǎng)上一個(gè)用遞歸的解法,很簡(jiǎn)潔。于是重寫了一遍。

class Solution(object):
 def combinationSum(self, candidates, target):
 """
 :type candidates: List[int]
 :type target: int
 :rtype: List[List[int]]
 """
 result,temp = [],[]
 self.combinationSumRecu(sorted(candidates),result,0,temp,target)
 return result

 def combinationSumRecu(self, candidates, result, start, temp, target):
 if target == 0:
  result.append(temp) # 注意此處不能直接append(temp),否則是淺拷貝,之后temp.pop()時(shí)會(huì)將result中的數(shù)也pop出來
 while start < len(candidates) and candidates[start]<=target:
  temp.append(candidates[start])
  self.combinationSumRecu(candidates, result, start, temp,target-candidates[start])
  temp.pop()
  start += 1

if __name__ == '__main__':
 print Solution().combinationSum([2,3,6,7],7)

一開始沒看懂combinationSumRecu中的result.append(list(temp))為什么temp要加list,因?yàn)閠emp本身就是一個(gè)list。但是把list去掉后,結(jié)果就出現(xiàn)錯(cuò)誤。

沒改前,結(jié)果是:

[[2, 2, 3], [7]]

改成result.append(temp)后:

[[], []]

為什么會(huì)這樣呢?list在這里做了什么工作呢?

首先,為了驗(yàn)證temp每步都是一個(gè)list,我們是使用type()函數(shù)查看它的類型。

if target == 0: 
 print type(temp),temp,result 
 result.append(temp) 

輸出為:

<type 'list'> [2, 2, 3] []
<type 'list'> [7] [[7]]

可以看出,temp都是list。但是第二個(gè)result的結(jié)果不正確

可以將正確的值輸出對(duì)比一下

if target == 0: 
 print type(temp),temp,result 
 result.append(list(temp)) 

輸出為:

<type 'list'> [2, 2, 3] []
<type 'list'> [7] [[7]]

可以看出,本來第二個(gè)result應(yīng)該為[[2,2,3]],結(jié)果變成了[[7]].

于是猜想可能是append()淺拷貝問題。

append(temp)后又在后面進(jìn)行temp.pop()操作。result實(shí)際上append的是temp的引用。當(dāng)temp所指向的地址的值發(fā)生改變時(shí),result也會(huì)跟著改變。

舉個(gè)例子驗(yàn)證一下:

a = [1,2] 
b = [3,4] 
a.append(b) 
print a 
b.pop() 
print a 

輸出結(jié)果為:

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

要解決這個(gè)問題,需要對(duì)temp進(jìn)行深拷貝后append到result中。而list(temp)就會(huì)返回temp的一個(gè)深拷貝。

除了用list(temp)以外,還可以用temp[:]進(jìn)行深拷貝。

以上這篇對(duì)python append 與淺拷貝的實(shí)例講解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI