【问题标题】:Converting integer to digit list [duplicate]将整数转换为数字列表[重复]
【发布时间】:2021-10-14 05:32:41
【问题描述】:

将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)) <map object at 0x1aed510> (我不知道如何格式化评论对。)
    • @GinKin 对于 Python 3,您需要 list(map(int, str(num)) )。
    • 更多关于答案的信息可以在这里找到:https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions 和这里https://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】:

      如果你有这样的字符串:'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']
      

      【讨论】:

        【解决方案6】:

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

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

        【讨论】:

        • @Tim:这没有给出一个 int 列表,而是一个字符串列表。
        【解决方案7】:
        >>>list(map(int, str(number)))  #number is a given integer
        

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

        【讨论】:

          【解决方案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 = 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。
              【解决方案11】:
              num = list(str(100))
              index = len(num)
              while index > 0:
                  index -= 1
                  num[index] = int(num[index])
              print(num)
              

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

              【讨论】:

                【解决方案12】:

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

                代码:

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

                使用 156789 输出:

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

                【讨论】:

                  猜你喜欢
                  • 2012-05-08
                  • 2023-03-13
                  • 2021-07-26
                  • 1970-01-01
                  • 2021-12-25
                  • 2010-10-21
                  • 2012-12-04
                  • 1970-01-01
                  相关资源
                  最近更新 更多