Re: [問題] 新手list問題請教消失

看板Python作者時間6年前 (2018/09/28 04:01), 6年前編輯推噓1(106)
留言7則, 2人參與, 最新討論串5/6 (看更多)
def increment(self, add=1, output=[]): for index, value in enumerate(self[::-1]): add += value * 10 ** (index) output.insert(0, (add // 10 ** index ) % 10) return output print(increment([0, 9, 9, 9]) 我的結構弄得比較複雜, 希望能再精進, 望版友不吝指正, 謝謝:-) ; 概念為: 將數列視為10為底的指數列, 並依位數加總運算 1. 預設arg: add=1 (whole list increment by 1), output (empty list) 2. 利用enumerate()及slicing[start:end:step]作數列運算-由各個位數加總 for index, value in enumerate(self[::-1]): >>> 0, 9 1, 9 2, 9 3, 0 依序為(倒數)第0項(start=0), 第0項值 3. 利用list.insert(index=0, x)特性及operator計算各位數的值 4. add值為總合 補充:參考cutekid版友所提供的運算法, 增加sling的結構, 控制output的數列規模, 運算式如下: def increment(self): num = int(''.join(str(x) for x in self)) num = num + 1 numList = list(str(num).zfill(len(self))) return [int(x) for x in numList[len(numList)-len(self):]] print(increment([0, 0, 9, 9])) print(increment([9, 9, 9, 9])) >>>[0, 1, 0, 0] >>>[0, 0, 0, 0] ※ 引述《rexyeah (ccccccc)》之銘言: : a = [0, 9, 9, 9] : def s(n): : return n+1 if n < 9 else (n+1) % 10 : print map(lambda x: s(x), a) : == : Output : [1, 0, 0, 0] : ※ 引述《cutekid (可愛小孩子)》之銘言: : : def increment(self): : : num = int(''.join(str(x) for x in self)) : : num = num + 1 : : numList = list(str(num).zfill(len(self))) : : return [int(x) for x in numList] : : print(increment([0,9,9,9])) : : 參考: : : 1. How to convert list to string [duplicate] : : https://bit.ly/2xz7uSj : : 2. Nicest way to pad zeroes to a string : : https://bit.ly/2IidRxs : : 3. how do I convert a string to a list : : https://bit.ly/2OQShTf -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.165.227.242 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1538078509.A.05C.html ※ 編輯: jasonislin (118.165.227.242), 09/28/2018 11:56:19

09/28 21:17, , 1F
預設參數的用法是錯的喔。
09/28 21:17, 1F

09/29 09:24, , 2F
謝謝您的指點,想麻煩您說明我錯誤的部分,以利我改進!
09/29 09:24, 2F

09/29 10:44, , 3F
output=[] 的部分,這樣寫的話每次 output 都會指向同一
09/29 10:44, 3F

09/29 10:44, , 4F
物件,導致每次函數結果會串接在一起。如果不知道在說什
09/29 10:44, 4F

09/29 10:44, , 5F
麼的話,多跑幾次 increment() 看看結果應該就知道了。
09/29 10:44, 5F

09/29 10:45, , 6F
傳統的作法是,參數預設 output=None,然後在函數裡檢查
09/29 10:45, 6F

09/29 10:45, , 7F
if output is None: output = []
09/29 10:45, 7F
文章代碼(AID): #1RhJSj1S (Python)
文章代碼(AID): #1RhJSj1S (Python)