从浮动列表中,如何在Python中只保留尾数?

5 python floating-point numpy

我有一个数字列表,我想从中返回一个mantissas列表:

get_mantissa([1.565888, 2.073744, 2.962492, 4.52838, 5.417127, 7.025337])
#[0.565888, 0.073744, 0.962492, 0.52838, 0.417127, 0.025337]
Run Code Online (Sandbox Code Playgroud)

所有帮助非常感谢.

ars*_*jii 5

你可以把你的所有数字改为1:

>>> l = [1.565888, 2.073744, 2.962492, 4.52838, 5.417127, 7.025337]
>>> 
>>> [a%1 for a in l]
[0.565888, 0.07374400000000003, 0.9624920000000001, 0.5283800000000003, 0.4171269999999998, 0.025337000000000387]
Run Code Online (Sandbox Code Playgroud)

如果你也要处理否定,那么a - int(a)应该这样做:

>>> [a - int(a) for a in l]  # works with negatives too
[0.565888, 0.07374400000000003, 0.9624920000000001, 0.5283800000000003, 0.4171269999999998, 0.025337000000000387]
Run Code Online (Sandbox Code Playgroud)

  • @JoeyDiNardo 正则表达式是用于处理字符串的工具。a 用于操作字符串。在大多数情况下,处理数字时,您会使用数学。 (2认同)