Re: [问题] 新手list问题请教

楼主: jasonislin (jason)   2018-09-28 04:01:46
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
作者: stucode   2018-09-28 21:17:00
默认参数的用法是错的喔。
楼主: jasonislin (jason)   2018-09-29 09:24:00
谢谢您的指点,想麻烦您说明我错误的部分,以利我改进!
作者: stucode   2018-09-29 10:44:00
output=[] 的部分,这样写的话每次 output 都会指向同一物件,导致每次函数结果会串接在一起。如果不知道在说什么的话,多跑几次 increment() 看看结果应该就知道了。传统的作法是,参数默认 output=None,然后在函数里检查if output is None: output = []

Links booklink

Contact Us: admin [ a t ] ucptt.com