【发布时间】:2016-04-02 09:18:14
【问题描述】:
为了生成 Numpy 索引,我需要将 float 舍入为 int。
在 Python 2.7 中,将 float 舍入得到 float:
>>> round(2.7)
3.0
在 Python 3.5 中,返回 int:
>>> round(2.7)
3
np.round() 总是返回一个浮点数。
int(round(2.7)) 是以 Python 2/3 兼容的方式舍入为整数的规范方法吗?
【问题讨论】:
-
不知道是不是规范,但这是我会做的。
-
如果给出单个参数,Python 3 将返回一个整数。否则类型匹配第一个参数的类型。例如,在 Python 3 中尝试
round(2.7, 0)。
标签: python python-2.7 python-3.x