所有
我想要定义一个 int(987654321)< => [9,8,7,6,5,4,3,2,1] 转换器,如果int数的长度< 9 ,例如 10 该列表将 [0,0,0,0,0,0,0,1,0] ,如果长度> 9,例如9987654321,列表将是[9,9,8,7,6,5,4,3,2,1]
>>> i
987654321
>>> l
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> z = [0]*(len(unit) - len(str(l)))
>>> z.extend(l)
>>> l = z
>>> unit
[100000000, 10000000, 1000000, 100000, 10000, 1000, 100, 10, 1]
>>> sum([x*y for x,y in zip(l, unit)])
987654321
>>> int("".join([str(x) for x in l]))
987654321
>>> l1 = [int(x) for x in str(i)]
>>> z = [0]*(len(unit) - len(str(l1)))
>>> z.extend(l1)
>>> l1 = z
>>> l1
[9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> a = [i//x for x in unit]
>>> b = [a[x] - a[x-1]*10 for x in range(9)]
>>> if len(b) = len(a): b[0] = a[0] # fix the a[-1] issue
>>> b
[9, 8, 7, 6, 5, 4, 3, 2, 1]
我测试了以上解决方案,但发现那些可能不比我想要的更快/更简单,并且内部可能有长度相关的错误,任何人都可以与我分享这种转换的更好的解决方案?
谢谢!
答案 0 :(得分:10)
也许我错过了一些东西,但这不应该足够(没有价值检查)?
def int_to_list(i):
return [int(x) for x in str(i).zfill(9)]
def list_to_int(l):
return int("".join(str(x) for x in l))
参考: str.zfill
答案 1 :(得分:1)
那怎么样:
def int_to_list(num)
return list ("%010d" % num)
答案 2 :(得分:0)
def convert(number):
stringified_number = '%s' % number
if len(stringified_number) < 9:
stringified_number = stringified_number.zfill(9)
return [int(c) for c in stringified_number]
>>> convert(10)
[0, 0, 0, 0, 0, 0, 0, 1, 0]
>>> convert(987654321)
[9, 8, 7, 6, 5, 4, 3, 2, 1]
答案 3 :(得分:0)
按整数位 -
将任意长度的整数按顺序放入列表中a = 123456789123456789123456789123456789123456789123456789
j = len('{}'.format(a))
b = [0 for i in range(j)]
c = 0
while j > 0:
b [c] = a % 10**j // 10**(j-1)
j = j-1
c = c + 1
print(b)
输出 -
[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5, 6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3, 4,5,6,7,8,9]
您可以将条件放在j上,以便将替代分配放到b。