在Python中,如何找到整数中的位数?
当前回答
顶部的答案是说mathlog10更快,但我得到的结果表明len(str(n))更快。
arr = []
for i in range(5000000):
arr.append(random.randint(0,12345678901234567890))
%%timeit
for n in arr:
len(str(n))
//2.72 s ± 304 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit
for n in arr:
int(math.log10(n))+1
//3.13 s ± 545 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
此外,我没有在数学方法中添加逻辑来返回准确的结果,我只能想象这会使它更加缓慢。
我不知道之前的答案是如何证明数学方法更快的。
其他回答
不需要转换为字符串
import math
digits = int(math.log10(n))+1
也可以处理0和负数
import math
if n > 0:
digits = int(math.log10(n))+1
elif n == 0:
digits = 1
else:
digits = int(math.log10(-n))+2 # +1 if you don't count the '-'
你可能想把它放在一个函数中:)
以下是一些基准测试。len(str())对于非常小的数字已经落后了
timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop
timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop
timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop
n = 3566002020360505
count = 0
while(n>0):
count += 1
n = n //10
print(f"The number of digits in the number are: {count}")
output: number中的位数为:16
对于整数,可以使用以下方法快速完成:
len(str(abs(1234567890)))
获取"1234567890"的绝对值的字符串长度。
abs返回没有任何负号的数字(只有数字的大小),str将其转换为字符串,len返回该字符串的字符串长度。
如果你想让它为浮点数工作,你可以使用以下任何一个:
# Ignore all after decimal place
len(str(abs(0.1234567890)).split(".")[0])
# Ignore just the decimal place
len(str(abs(0.1234567890)))-1
供以后参考。
from math import log10
digits = lambda n: ((n==0) and 1) or int(log10(abs(n)))+1
这是另一种计算任何数字的小数点前的位数的方法
from math import fabs
len(format(fabs(100),".0f"))
Out[102]: 3
len(format(fabs(1e10),".0f"))
Out[165]: 11
len(format(fabs(1235.4576),".0f"))
Out[166]: 4
我做了一个简短的基准测试,进行了10,000次循环
num len(str(num)) ---- len(format(fabs(num),".0f")) ---- speed-up
2**1e0 2.179400e-07 sec ---- 8.577000e-07 sec ---- 0.2541
2**1e1 2.396900e-07 sec ---- 8.668800e-07 sec ---- 0.2765
2**1e2 9.587700e-07 sec ---- 1.330370e-06 sec ---- 0.7207
2**1e3 2.321700e-06 sec ---- 1.761305e-05 sec ---- 0.1318
这是一个较慢但更简单的选择。
但是即使这个解也会给出错误的99999999999998
len(format(fabs(9999999999999998),".0f"))
Out[146]: 16
len(format(fabs(9999999999999999),".0f"))
Out[145]: 17
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 确定记录是否存在的最快方法
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if