我有一个数字列表,我想从中返回一个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]
所有人都非常感谢。
答案 0 :(得分: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]
如果你也要处理否定词,那么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]
答案 1 :(得分:2)
这是另一种使用numpy的方法。还需要考虑的是如何处理负数。
import numpy as np
a = np.array([1.234, 5.678, -9.012])
print a % 1
# [ 0.234 0.678 0.988]
print a % np.sign(a)
# [ 0.234 0.678 -0.012]
答案 2 :(得分:2)
在numpy中你有np.modf
比你想要的更多:
>>> np.modf([1.565888, 2.073744, 2.962492, 4.52838, 5.417127, 7.025337])
(array([ 0.565888, 0.073744, 0.962492, 0.52838 , 0.417127, 0.025337]),
array([ 1., 2., 2., 4., 5., 7.]))
所以这会给你你想要的结果:
>>> np.modf([1.565888, 2.073744, 2.962492, 4.52838, 5.417127, 7.025337])[0]
array([ 0.565888, 0.073744, 0.962492, 0.52838 , 0.417127, 0.025337])