convert an int to list of individual digitals more faster?

a 夏天 提交于 2019-12-23 02:32:26

问题


All,

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?

Thanks!


回答1:


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))

Reference: str.zfill




回答2:


And what about :

def int_to_list(num)
    return list ("%010d" % num)



回答3:


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]



回答4:


To place an integer of any length into a list in sequence by integer digit -

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)

output -

[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]

you can put the condition on j for the alternate assignment to b.



来源:https://stackoverflow.com/questions/5242798/convert-an-int-to-list-of-individual-digitals-more-faster

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!