Convert a number to a list of integers

前端 未结 11 1410
渐次进展
渐次进展 2020-12-03 02:44

How do I write the magic function below?

>>> num = 123
>>> lst = magic(num)
>>>
>>> print lst, type(lst)
[1,         


        
相关标签:
11条回答
  • 2020-12-03 03:05
    num = map(int, list(str(num)))
    
    0 讨论(0)
  • 2020-12-03 03:06
    a = 123456
    b = str(a)
    c = []
    
    for digit in b:
        c.append (int(digit))
    
    print c
    
    0 讨论(0)
  • 2020-12-03 03:13

    You mean this?

    num = 1234
    lst = [int(i) for i in str(num)]
    
    0 讨论(0)
  • 2020-12-03 03:15

    Just use :

    a= str (num)
    lst = list(a)
    
    0 讨论(0)
  • 2020-12-03 03:16

    If it is named as magic, why not just use magic:

    def magic(x):
        if x < 10:
            return [x]
        else:
            return magic(x//10) + [x%10]
    
    0 讨论(0)
  • 2020-12-03 03:22
    magic = lambda num: map(int, str(num))
    

    then just do

    magic(12345) 
    

    or

    magic(someInt) #or whatever
    
    0 讨论(0)
提交回复
热议问题