gpt4 book ai didi

python - 为什么python截断 float 到整数?

转载 作者:行者123 更新时间:2023-12-04 07:52:27 25 4
gpt4 key购买 nike

我想知道为什么每当我将浮点数分配给 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 会在分配给数组(包含整数)之前将浮点数转换为整数。

最佳答案

尝试:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com