我想知道为什么每当我将 float 分配给 numpy 数组时,Python 都会将数字截断为整数:
import numpy as np
lst = np.asarray(list(range(10)))
print ("lst before assignment: ", lst)
lst[:4] = [0.3, 0.5, 10.6, 0.2];
print ("lst after assignment: ", lst)
输出:
lst before assignment: [0 1 2 3 4 5 6 7 8 9]
lst after assignment: [ 0 0 10 0 4 5 6 7 8 9]
为什么要这样做?由于您不需要在语言中指定类型,因此我无法理解为什么 numpy 在分配给数组(包含整数)之前将 float 转换为整数。
最佳答案
尝试:
lst = np.asarray(list(range(10)), dtype=float)
lst before assignment: [0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]
lst after assignment: [ 0.3 0.5 10.6 0.2 4. 5. 6. 7. 8. 9. ]
关于python - 为什么python截断 float 为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66888063/