Converting integer to digit list

前端 未结 10 1095
渐次进展
渐次进展 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条回答
  •  萌比男神i
    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.

提交回复
热议问题