这个页面上已经提到了很多很棒的方法,但是对于使用哪个似乎有点模糊。因此,我添加了一些测量方法,以便您更轻松地自行决定:
大量已被使用(用于开销)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)) 的方法可能是两者中最理想的。
那些重新发明轮子的东西很有趣,但在实际使用中可能并不那么理想。