将int转换为单个数字列表更快? [英] convert an int to list of individual digitals more faster?
问题描述
全部,
我想要定义一个 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 want define an int(987654321) <=> [9, 8, 7, 6, 5, 4, 3, 2, 1] convertor, if the length of int number < 9, for example 10 the list will be [0,0,0,0,0,0,0,1,0] , and if the length > 9, for example 9987654321 , the list will be [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]
我测试了以上解决方案,但发现那些可能不比我想要的更快/更简单,并且可能内部有长度相关的错误,任何人都可以与我分享这种转换的更好的解决方案?
I tested above solutions but found those may not faster/simple enough than I want and may have a length related bug inside, anyone may share me a better solution for this kinds convertion?
谢谢!
推荐答案
也许我错过了什么,但这不应该是足够的(没有价值检查) ?
Maybe I am missing something, but shouldn't this be enough (without value checking)?
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
这篇关于将int转换为单个数字列表更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!