【问题标题】:Converting integer to digit list将整数转换为数字列表
【发布时间】:2012-12-04 01:31:21
【问题描述】:

integer 转换为list 的最快和最干净的方法是什么?

例如,将132 更改为[1,3,2],将23 更改为[2,3]。我有一个变量是int,我希望能够比较各个数字,所以我认为将其放入列表中是最好的,因为我可以通过int(number[0])int(number[1]) 轻松转换将元素列表放回 int 以进行数字操作。

【问题讨论】:

标签: python list integer type-conversion


【解决方案1】:

先把整数转成字符串,然后用map在上面应用int

>>> num = 132
>>> map(int, str(num))    #note, This will return a map object in python 3.
[1, 3, 2]

或使用列表推导:

>>> [int(x) for x in str(num)]
[1, 3, 2]

【讨论】:

  • 我试过你写的,但它没有返回和你一样的结果: >>>num =132 >>>map(int, str(num)) (我不知道如何正确格式化评论。)
  • @GinKin 对于 Python 3,您需要 list(map(int, str(num)) )
  • 更多的答案可以在这里找到:https://docs.python.org/3/tutorial/datastructures.html#list-comprehensionshttps://en.wikipedia.org/wiki/List_comprehension
【解决方案2】:

这个页面上已经提到了很多很棒的方法,但是对于使用哪个似乎有点模糊。因此,我添加了一些测量方法,以便您更轻松地自行决定:


大量已被使用(用于开销)1111111111111122222222222222222333333333333333333333

使用map(int, str(num)):

import timeit

def method():
    num = 1111111111111122222222222222222333333333333333333333
    return map(int, str(num))

print(timeit.timeit("method()", setup="from __main__ import method", number=10000)

输出:0.018631496999999997

使用列表理解:

导入时间

def method():
    num = 1111111111111122222222222222222333333333333333333333
    return [int(x) for x in str(num)]

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

输出:0.28403817900000006

代码取自this answer

结果表明,第一种涉及内置方法的方法比列表理解要快得多。

“数学方式”:

import timeit

def method():
    q = 1111111111111122222222222222222333333333333333333333
    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(timeit.timeit("method()", setup="from __main__ import method", number=10000))

输出:0.38133582499999996

代码取自this answer

list(str(123)) 方法(不提供正确的输出):

import timeit

def method():
    return list(str(1111111111111122222222222222222333333333333333333333))
    
print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

输出:0.028560138000000013

代码取自this answer

Duberly González Molinari 的回答:

import timeit

def method():
    n = 1111111111111122222222222222222333333333333333333333
    l = []
    while n != 0:
        l = [n % 10] + l
        n = n // 10
    return l

print(timeit.timeit("method()", setup="from __main__ import method", number=10000))

输出:0.37039988200000007

代码取自this answer

备注:

在所有情况下,map(int, str(num)) 是最快的方法(因此可能是最好的使用方法)。列表理解是第二快的(但使用map(int, str(num)) 的方法可能是两者中最理想的。

那些重新发明轮子的东西很有趣,但在实际使用中可能并不那么理想。

【讨论】:

    【解决方案3】:

    最短最好的方法已经回答了,但是我首先想到的是数学方法,所以这里是:

    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)
    

    这只是另一种有趣的方法,您绝对不必在实际用例中使用这样的东西。

    【讨论】:

    • list.insert(0, item)O(n) 操作。您可以改用list.append(item) 并在末尾反转列表:ret[::-1]
    • 只是应该注意这对于 0 失败
    【解决方案4】:
    n = int(raw_input("n= "))
    
    def int_to_list(n):
        l = []
        while n != 0:
            l = [n % 10] + l
            n = n // 10
        return l
    
    print int_to_list(n)
    

    【讨论】:

    • 请添加解释,而不仅仅是代码。解释它的作用。
    【解决方案5】:
    >>>list(map(int, str(number)))  #number is a given integer
    

    它返回数字的所有数字的列表。

    【讨论】:

      【解决方案6】:

      如果你有这样的字符串:'123456' 你想要一个这样的整数列表:[1,2,3,4,5,6],使用这个:

      >>>s = '123456'    
      >>>list1 = [int(i) for i in list(s)]
      >>>print(list1)
      
      [1,2,3,4,5,6]
      

      或者如果你想要这样的字符串列表:['1','2','3','4','5','6'],使用这个:

      >>>s = '123456'    
      >>>list1 = list(s)
      >>>print(list1)
      
      ['1','2','3','4','5','6']
      

      【讨论】:

        【解决方案7】:

        在转换为字符串的数字上使用list

        In [1]: [int(x) for x in list(str(123))]
        Out[2]: [1, 2, 3]
        

        【讨论】:

        • @Tim:这并没有给出一个 int 列表,而是一个字符串列表。
        【解决方案8】:

        你可以使用:

        首先转换字符串中的值进行迭代,每个值都可以转换为整数value = 12345

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

        【讨论】:

          【解决方案9】:

          通过循环,可以通过以下方式完成:)

          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)
          

          答案变成了

          Enter the number2342
          [2, 3, 4, 2]
          

          【讨论】:

            【解决方案10】:
            num = list(str(100))
            index = len(num)
            while index > 0:
                index -= 1
                num[index] = int(num[index])
            print(num)
            

            它打印[1, 0, 0] 对象。

            【讨论】:

              【解决方案11】:

              将一个整数作为输入并将其转换为数字列表。

              代码:

              num = int(input())
              print(list(str(num)))
              

              使用 156789 输出:

              >>> ['1', '5', '6', '7', '8', '9']
              

              【讨论】:

                【解决方案12】:
                num = 123
                print(num)
                num = list(str(num))
                num = [int(i) for i in num]
                print(num)
                

                【讨论】:

                • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
                • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
                猜你喜欢
                • 2010-10-21
                • 1970-01-01
                • 1970-01-01
                • 2014-10-17
                • 1970-01-01
                • 1970-01-01
                • 2021-10-14
                相关资源
                最近更新 更多