将integer转换为list的最快、最干净的方法是什么?
例如,将132更改为[1,3,2],将23更改为[2,3]。我有一个变量,它是一个整数,我想能够比较各个数字,所以我认为把它变成一个列表是最好的,因为我可以做int(number[0]),int(number[1]),来轻松地将列表元素转换回int,进行数字操作。
发布于 2012-12-17 06:07:11
首先将整数转换为字符串,然后使用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]发布于 2012-12-17 06:34:00
最短最好的方法已经回答了,但我首先想到的是数学方法,所以它是这样的:
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)这只是另一种有趣的方法,你绝对不需要在实际用例中使用这样的东西。
发布于 2017-07-28 23:45:56
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)https://stackoverflow.com/questions/13905936
复制相似问题