简体   繁体   中英

convert an int to list of individual digitals more faster?

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!

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

And what about :

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

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM