Der*_*yll 39 python integer list type-conversion
将一个转换integer
成一个最快,最干净的方法是list
什么?
例如,改变132
进入[1,3,2]
和23
进入[2,3]
.我有一个变量,它是一个int
,我希望能够以比较个别数字,所以我想使它成为一个名单将是最好的,因为我可以做int(number[0])
,int(number[1])
可以轻松地转换列表元素回int对于数字业务.
Ash*_*ary 72
首先将整数转换为字符串,然后使用它map
来应用int
:
>>> num = 132
>>> map(int, str(num)) #note, This will return a map object in python 3.
[1, 3, 2]
Run Code Online (Sandbox Code Playgroud)
或使用列表理解:
>>> [int(x) for x in str(num)]
[1, 3, 2]
Run Code Online (Sandbox Code Playgroud)
Sim*_*mon 12
此页面上已经提到了一些很棒的方法,但是对于使用哪种方法似乎有点模糊。所以我添加了一些测量,以便您可以更轻松地自己决定:
大量使用(用于开销) 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)
Run Code Online (Sandbox Code Playgroud)
输出: 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))
Run Code Online (Sandbox Code Playgroud)
输出: 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))
Run Code Online (Sandbox Code Playgroud)
输出: 0.38133582499999996
取自此答案的代码
list(str(123))
方法(不提供正确的输出):import timeit
def method():
return list(str(1111111111111122222222222222222333333333333333333333))
print(timeit.timeit("method()", setup="from __main__ import method", number=10000))
Run Code Online (Sandbox Code Playgroud)
输出: 0.028560138000000013
取自此答案的代码
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))
Run Code Online (Sandbox Code Playgroud)
输出: 0.37039988200000007
取自此答案的代码
在所有情况下,这map(int, str(num))
是最快的方法(因此可能是最好的方法)。列表理解是第二快的(但使用的方法map(int, str(num))
可能是两者中最理想的。
那些重新发明轮子的东西很有趣,但在实际使用中可能不太理想。
最短最好的方法已经回答了,但我想到的第一件事就是数学方法,所以这里是:
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)
Run Code Online (Sandbox Code Playgroud)
这只是另一个有趣的方法,你绝对不必在实际使用案例中使用这样的东西.