看板 Python 關於我們 聯絡資訊
大家好 最近在刷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
mikapauli: 複製的意思,或是用cach.copy()、cach[:]、list(cach) 07/05 10:41
mikapauli: 、tuple(cach)等都可以。 07/05 10:41
typhoonss821: 請問是因為list的mutable性質所以改變cach也會改變 07/05 10:51
typhoonss821: 之前的result.append嗎? 07/05 10:51
Yshuan: 是function的mutable arguments特性 建議避免 07/05 11:23
Yshuan: 必須用的話, 最安全就是caller或callee去做copy 07/05 11:24
typhoonss821: 非常感謝兩位的回答 07/05 12:31
pmove: 原來+[]是這個意思,之前比較常見的是cach[:] 07/05 12:52
handsomeLin: 因為你塞同一個reference進去 在result裡的結果會都 07/05 23:02
handsomeLin: 一樣 相當於copy沒錯 07/05 23:02