[問題] append(element+[])

看板Python作者 (jeff)時間7年前 (2018/07/05 10:33), 編輯推噓2(208)
留言10則, 5人參與, 7年前最新討論串1/1
大家好 最近在刷leetcode 寫到一題給出一組數列 求所有permutations的可能 https://leetcode.com/problems/permutations/description/ 我的code是這樣的,主體無窮遞迴的方式求解 class Solution: def getSolution(self, x): cach = [] result = [] self.permutations(x, cach, result) return result def permutations(self, x, cach, result): if len(x) == 0: result.append(cach) for i in range(len(x)): cach.append(x[i]) self.permutations(x[:i]+x[i+1:], cach, result) cach.pop() 但我發現在上色部分append完的result在下一次append前他的值都會自動被改變 而我google了使用一樣解法的code,發現只要將append(cach)改成append(cach+[]) 這樣的輸出就不會有值被改變的問題 我查了半天找不到類似的解釋 不太知道+[]的用意是什麼 所以來這邊請教大家 先謝謝大家的回答了! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 72.229.255.136 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1530758013.A.931.html

07/05 10:41, 7年前 , 1F
複製的意思,或是用cach.copy()、cach[:]、list(cach)
07/05 10:41, 1F

07/05 10:41, 7年前 , 2F
、tuple(cach)等都可以。
07/05 10:41, 2F

07/05 10:51, 7年前 , 3F
請問是因為list的mutable性質所以改變cach也會改變
07/05 10:51, 3F

07/05 10:51, 7年前 , 4F
之前的result.append嗎?
07/05 10:51, 4F

07/05 11:23, 7年前 , 5F
是function的mutable arguments特性 建議避免
07/05 11:23, 5F

07/05 11:24, 7年前 , 6F
必須用的話, 最安全就是caller或callee去做copy
07/05 11:24, 6F

07/05 12:31, 7年前 , 7F
非常感謝兩位的回答
07/05 12:31, 7F

07/05 12:52, 7年前 , 8F
原來+[]是這個意思,之前比較常見的是cach[:]
07/05 12:52, 8F

07/05 23:02, 7年前 , 9F
因為你塞同一個reference進去 在result裡的結果會都
07/05 23:02, 9F

07/05 23:02, 7年前 , 10F
一樣 相當於copy沒錯
07/05 23:02, 10F
文章代碼(AID): #1RFODzan (Python)
文章代碼(AID): #1RFODzan (Python)