Converting integer to digit list

前端 未结 10 1084
渐次进展
渐次进展 2020-11-30 23:45

What is the quickest and cleanest way to convert an integer into a list?

For example, change 132 into [1,3,2] an

相关标签:
10条回答
  • 2020-12-01 00:14
    >>>list(map(int, str(number)))  #number is a given integer
    

    It returns a list of all digits of number.

    0 讨论(0)
  • 2020-12-01 00:17

    By looping it can be done the following way :)

    num1= int(input('Enter the number'))
    sum1 = num1 #making a alt int to store the value of the orginal so it wont be affected
    y = [] #making a list 
    while True:
        if(sum1==0):#checking if the number is not zero so it can break if it is
            break
        d = sum1%10 #last number of your integer is saved in d
        sum1 = int(sum1/10) #integer is now with out the last number ie.4320/10 become 432
        y.append(d) # appending the last number in the first place
    
    y.reverse()#as last is in first , reversing the number to orginal form
    print(y)
    

    Answer becomes

    Enter the number2342
    [2, 3, 4, 2]
    
    0 讨论(0)
  • 2020-12-01 00:18

    The shortest and best way is already answered, but the first thing I thought of was the mathematical way, so here it is:

    def intlist(n):
        q = n
        ret = []
        while q != 0:
            q, r = divmod(q, 10) # Divide by 10, see the remainder
            ret.insert(0, r) # The remainder is the first to the right digit
        return ret
    
    print intlist(3)
    print '-'
    print intlist(10)
    print '--'
    print intlist(137)
    

    It's just another interesting approach, you definitely don't have to use such a thing in practical use cases.

    0 讨论(0)
  • 2020-12-01 00:18

    you can use:

    First convert the value in a string to iterate it, Them each value can be convert to a Integer value = 12345

    l = [ int(item) for item in str(value) ]

    0 讨论(0)
提交回复
热议问题