對python append 與淺拷貝的實例講解
在做Leetcode的第39題的時候,看到網(wǎng)上一個用遞歸的解法,很簡潔。于是重寫了一遍。
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中的數(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,因為temp本身就是一個list。但是把list去掉后,結(jié)果就出現(xiàn)錯誤。
沒改前,結(jié)果是:
[[2, 2, 3], [7]]
改成result.append(temp)后:
[[], []]
為什么會這樣呢?list在這里做了什么工作呢?
首先,為了驗證temp每步都是一個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。但是第二個result的結(jié)果不正確
可以將正確的值輸出對比一下
if target == 0: print type(temp),temp,result result.append(list(temp))
輸出為:
<type 'list'> [2, 2, 3] [] <type 'list'> [7] [[7]]
可以看出,本來第二個result應(yīng)該為[[2,2,3]],結(jié)果變成了[[7]].
于是猜想可能是append()淺拷貝問題。
append(temp)后又在后面進(jìn)行temp.pop()操作。result實際上append的是temp的引用。當(dāng)temp所指向的地址的值發(fā)生改變時,result也會跟著改變。
舉個例子驗證一下:
a = [1,2] b = [3,4] a.append(b) print a b.pop() print a
輸出結(jié)果為:
[1, 2, [3, 4]] [1, 2, [3]]
要解決這個問題,需要對temp進(jìn)行深拷貝后append到result中。而list(temp)就會返回temp的一個深拷貝。
除了用list(temp)以外,還可以用temp[:]進(jìn)行深拷貝。
以上這篇對python append 與淺拷貝的實例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
通過實例解析python subprocess模塊原理及用法
這篇文章主要介紹了通過實例解析python subprocess模塊原理及用法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-10-10解決pytorch下只打印tensor的數(shù)值不打印出device等信息的問題
這篇文章主要介紹了解決pytorch下只打印tensor的數(shù)值不打印出device等信息的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-05-05C++通過內(nèi)嵌解釋器調(diào)用Python及間接調(diào)用Python三方庫
本文主要介紹了C++通過內(nèi)嵌解釋器調(diào)用Python及間接調(diào)用Python三方庫,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-12-12windows系統(tǒng)下Python環(huán)境的搭建(Aptana Studio)
這篇文章主要介紹了windows系統(tǒng)下Python環(huán)境的搭建(Aptana Studio),需要的朋友可以參考下2017-03-03Django定制Admin頁面詳細(xì)實例(展示頁面和編輯頁面)
django自帶的admin因為功能和樣式比較簡陋,常常需要再次定制,下面這篇文章主要給大家介紹了關(guān)于Django定制Admin頁面(展示頁面和編輯頁面)的相關(guān)資料,需要的朋友可以參考下2023-06-06