Python 找到小数点后第一个非零数字
这是一个简单的问题,怎么找到小数点后第一个非零数字的位置。其实我想要的是小数点到第一个非零数字之间的距离。
我知道可以用几行代码来解决这个问题,但我希望能用一种更优雅、干净的方式来用Python实现。
到目前为止,我有这个
>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]
4 个回答
2
虽然技术上可以用一行代码(不算导入语句)来完成这个,但我加了一些额外的内容,让它看起来更完整。
from re import search
# Assuming number is already defined.
# Floats always have a decimal in its string representation.
if isinstance(float, number):
# This gets the substring of zeros immediately following the decimal point
# and returns the length of it.
return len(search("\.(0*)", "5.00060030").group(1))
else:
return -1
# or you can use raise TypeError() if you wanna be more restrictive.
这可能对你来说没什么关系,但我还是想提一下,以便更全面。在某些地区,数字的写法中小数点和逗号是颠倒的。比如说,1,000,000.00 在某些地方可能写成 1.000.000,00。我不确定 Python 是否会考虑到这一点,因为它在表示数字时不使用千位分隔符。如果你在其他地区使用,可以用模式 ,(0*)
。再次强调,这可能对你没什么影响,但对其他读者可能有用。
6
一种关注小数点后数字的方法是去掉数字的整数部分,只保留小数部分,可以用类似 x - int(x)
的方式来实现。
在分离出小数部分后,你可以让 Python 帮你进行计数,使用 %e
的格式,这样也能帮助解决一些四舍五入的问题。
>>> '%e' % 0.000125
'1.250000e-04'
>>> int(_.partition('-')[2]) - 1
3
10
最简单的方法似乎是
x = 123.0
dist = int(math.log10(abs(x)))
我把列表 t
中每对数据的第二个值看作你想要的结果,所以我选择了 int()
来让对数值向零靠近:
>>> [(int(math.log10(abs(x))), y) for x, y in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, -1), (-4, -4)]