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

首頁 > 編程 > Python > 正文

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

2020-01-04 15:13:29
字體:
來源:轉載
供稿:網友

在做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 與淺拷貝的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 伊宁县| 额尔古纳市| 当涂县| 巴彦淖尔市| 甘孜| 讷河市| 金川县| 盐边县| 新民市| 南通市| 榆林市| 胶南市| 西充县| 综艺| 沭阳县| 南漳县| 梅州市| 登封市| 鸡西市| 三门峡市| 杭州市| 康马县| 旌德县| 聊城市| 渝中区| 镇巴县| 赣州市| 肃宁县| 山丹县| 成安县| 商河县| 永定县| 五华县| 城步| 龙州县| 澄迈县| 巴彦淖尔市| 柘荣县| 荆门市| 凤庆县| 拜城县|