python在小数点后找到第一个非零数字

Fac*_*sco 6 python string floating-point

简单的问题,如何找到小数点后的第一个非零数字.我真正需要的是小数点和第一个非零数字之间的距离.

我知道我可以用几行来做,但我想要一些pythonic,漂亮和干净的方法来解决这个问题.

到目前为止,我有这个

>>> 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)]
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 6

最简单的方法似乎是

x = 123.0
dist = int(math.log10(abs(x)))
Run Code Online (Sandbox Code Playgroud)

我将每对列表中的第二个条目解释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)]
Run Code Online (Sandbox Code Playgroud)

  • 务必使用abs防止负值(不能记录它们). (2认同)
  • log(0)也不是那么好.OP可能需要特殊情况下这个值(提高ValueError或返回无穷大?). (2认同)
  • 我使用 `math.floor` 代替 `int` 来获得更一致的结果 (2认同)

Ray*_*ger 5

关注小数点后的数字的一种方法是删除数字的整数部分,留在小数部分,类似于x - int(x).

隔离了小数部分后,你可以让python通过%e演示为你做计数(这也有助于处理舍入问题).

>>> '%e' % 0.000125
'1.250000e-04'
>>> int(_.partition('-')[2]) - 1
3
Run Code Online (Sandbox Code Playgroud)