将整数转换为数字列表

68
什么是将一个整数转换为列表的最快且最简洁的方法?
例如,将132变成[1,3,2],将23变成[2,3]。我有一个变量是一个int,我想比较每个数字,所以我认为将其转换为列表是最好的,因为我可以使用 int(number[0])int(number[ 1 ]) 轻松地将列表元素转换回int,并进行数字运算。
12个回答

99

先将整数转换为字符串,然后使用mapint应用于它:

首先将该整数转换成字符串,然后使用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]

4
我试了一下你写的代码,但它没有像你的那样返回相同的结果:
num =132 map(int, str(num)) <map object at 0x1aed510> (我不知道如何正确格式化注释。)
- GinKin
4
对于 Python 3,您需要使用 list(map(int, str(num))) - Ashwini Chaudhary
更多关于答案的内容可在此处找到:https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions 和这里 https://en.wikipedia.org/wiki/List_comprehension - Wachaga Mwaura

20

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


已使用一个大数字(用于开销)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

使用列表推导式:

导入 timeit 模块

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

代码来自这个答案

结果显示,使用内置方法的第一种方法比列表推导快得多。

“数学方法”:

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

代码来自这个答案

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

import timeit

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

输出:0.028560138000000013

代码取自这个答案

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

代码来源于此答案

备注:

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

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


6

最短且最好的方法已经被回答了,但我首先想到的是数学方法,因此在这里介绍一下:

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)

这只是另一种有趣的方法,你在实际使用中完全不需要使用这样的东西。


2
list.insert(0, item) 是一个 O(n) 的操作。你可以使用 list.append(item),然后在最后反转列表:ret[::-1] - jfs
2
只需注意,这对于0会失败。 - anishtain4

3
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)

3
请添加解释而不仅仅是代码。解释它的作用是什么。 - MLavrentyev

2

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

2
>>>list(map(int, str(number)))  #number is a given integer

它返回一个数字的所有数字列表。最初的回答:

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


2

将数字转换为字符串后,使用list

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

14
@Tim:这不是一个整数列表,而是一个字符串列表。 - Benjamin Bannier

1

你可以使用:

首先将数值转换为字符串以进行迭代,然后将每个值转换为整数 value = 12345

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


1
通过循环可以这样做 :)
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]

0
num = 123
print(num)
num = list(str(num))
num = [int(i) for i in num]
print(num)

2
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心中找到有关如何编写良好答案的更多信息。 - Community
目前你的回答不够清晰,请编辑并添加更多细节,以帮助其他人理解它如何回答问题。你可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接