国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

對python append 與淺拷貝的實例講解

2020-02-22 23:59:49
字體:
來源:轉載
供稿:網友

在做Leetcode的第39題的時候,看到網上一個用遞歸的解法,很簡潔。于是重寫了一遍。

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()時會將result中的數也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 += 1if __name__ == '__main__': print Solution().combinationSum([2,3,6,7],7)

一開始沒看懂combinationSumRecu中的result.append(list(temp))為什么temp要加list,因為temp本身就是一個list。但是把list去掉后,結果就出現錯誤。

沒改前,結果是:

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

改成result.append(temp)后:

[[], []]

為什么會這樣呢?list在這里做了什么工作呢?

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

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

輸出為:

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

可以看出,temp都是list。但是第二個result的結果不正確

可以將正確的值輸出對比一下

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

輸出為:

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

可以看出,本來第二個result應該為[[2,2,3]],結果變成了[[7]].

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

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

舉個例子驗證一下:

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

輸出結果為:

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

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

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

以上這篇對python append 與淺拷貝的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 永年县| 米脂县| 辰溪县| 巧家县| 富顺县| 翁源县| 亳州市| 阳东县| 定陶县| 云南省| 哈巴河县| 烟台市| 武平县| 巢湖市| 浠水县| 寻乌县| 定南县| 朝阳区| 剑河县| 和硕县| 邵东县| 梓潼县| 肥乡县| 浦城县| 顺平县| 宝丰县| 潜江市| 五指山市| 广宗县| 图片| 永年县| 黄龙县| 宣汉县| 贵港市| 和政县| 利川市| 利川市| 花垣县| 平乐县| 乌鲁木齐县| 衡东县|