gpt4 book ai didi

python - 以 Python2 和 Python3 兼容的方式舍入 float 并将其转换为整数

转载 作者:行者123 更新时间:2023-11-28 19:13:38 25 4
gpt4 key购买 nike

为了生成 Numpy 索引,我需要将 float 舍入为 int

在 Python 2.7 中,舍入一个 float 得到一个 float:

>>> round(2.7)
3.0

在 Python 3.5 中,返回一个 int:

>>> round(2.7)
3

np.round() 总是返回一个 float 。

int(round(2.7)) 是以 Python 2/3 兼容方式舍入为整数的规范方法吗?

最佳答案

int(round(2.7)) 适用于两个版本。这里提出了一个类似的问题,但仅适用于 Python 2.7: Python 2.7: round number to nearest integer- 所以我会使用 int(round(x))

关于python - 以 Python2 和 Python3 兼容的方式舍入 float 并将其转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36371424/

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